How To Get Many To Many Model Field Values In Django View

We have learned how to add many to many fields for Django models in the article How To Operate Foreign Key And Many To Many Field In Django Model. But when we display the many to many field values ( in this example is the Employee’s Department values ) in Django Html template page, we find the employee’s department ( one employee can belong to multiple departments) value can not be displayed use Django template code like <td>{{ emp.dept }}</td>or <td>{{ emp.dept.dept_name }}</td>.

This article will tell you how to get the Django model many to many field values and display it on the Html template page. This example’s source code is based on How To Operate Foreign Key And Many To Many Field In Django Model source code.

1. Define A Model Method To Calculate And Return Many To Many Field Values.

  1. If we use <td>{{ emp.dept }}</td>or <td>{{ emp.dept.dept_name }}</td> in the Django app Html template page, the employee belonged department values can not be shown on the page.
  2. When you browse the employee list page with the URL http://127.0.0.1:8000/dept_emp/emp_list/, you will find the department column value for the employee jerry is empty.
  3. To fix this error, you should define a method in the Employee model class, and calculate the employee belongs departments, and return it’s value.
  4. Edit Employee model class source code in DjangoHelloWorld / dept_emp / models.py file and add the method get_dept_values.
    def get_dept_values(self):
    
        ret = ''
    
        print(self.dept.all())
    
        # use models.ManyToMany field's all() method to return all the Department objects that this employee belongs to.
        for dept in self.dept.all():
            ret = ret + dept.dept_name + ','
    
        # remove the last ',' and return the value.
        return ret[:-1]

2. Call Above Model Method In Html Template Page.

  1. Now you can call the Employee model class’s get_dept_values method on the Html template page.
  2. Edit DjangoHelloWorld / templates / dept_emp / emp_list.html page like below. Please note we call {{ emp.get_dept_values }} in the template page directly.
     {% for emp in emp_list %}
       <tr>
         <td><input type="checkbox" id="emp_{{ emp.id }}" name="emp_{{ emp.id }}"></td>
         <td>{{ emp.id }}</td>
         <td>{{ emp.user.username }}</td>
         <td>{{ emp.get_dept_values }}</td>
         <td>{{ emp.emp_mobile }}</td>
         <td>{{ emp.emp_salary }}</td>
         <td>{{ emp.emp_onboard_date }}</td>
       </tr>
    {% endfor %}

3. Run The Example To Display Model Class’s Many To Many Field Values.

  1. Now run the example and add one employee and two departments follow the below steps.
  2. Open a terminal and go to the DjangoHelloWorld Django project root folder.
  3. Run $ python3 manage.py shell command to open the Django project shell console.
  4. Then run the below code to add two exist departments to exist employee jerry.
    $ python3 manage.py shell
    
    # import Employee and Department model class.
    from dept_emp.models import Employee, Department
    
    # before run below code, you should make sure the following employee and departments exist, if not add them by example gui web page.
    # get exist employee jerry object.
    emp = Employee.objects.get(user__username='jerry')
    emp
    <Employee: jerry,100000,13901234567>
    
    # get the first department.
    dept_1 = Department.objects.get(id=1)
    dept_1
    <Department: Develop,Develop web site use Python Django>
    
    # get the second department
    dept_2 = Department.objects.get(id=2)
    dept_2
    <Department: Quality Assurance,Responsible for company website quality and test.>
    
    # add the two departments to the employee's departments.
    emp.dept.add(dept_1)
    emp.dept.add(dept_2)
    
    # save the employee object to save the two added department that jerry belongs to.
    emp.save()
  5. Now start the Django project server and browse the URL http://127.0.0.1:8000/dept_emp/emp_list/, you can see two departments in the employee list page that jerry belongs to like below.
    employee-list-page-show-employee-belongs-multiple-departments

1 thought on “How To Get Many To Many Model Field Values In Django View”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.