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

We have learnt how to add many to many fileds for django models in article How To Operate Foreign Key And Many To Many Field In Django Model. But when we display the many to many filed values ( in this example is the Employee’s Department values ) in django html template page, we find the employee’s department ( one employee can belongs to multiple department ) 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 in 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.

If we use <td>{{ emp.dept }}</td>or <td>{{ emp.dept.dept_name }}</td> in Django app html template page, the employee belongs department values can not be shown in the page, when you browse employee list page url, you will get below picture. The department column value is empty.

employee list page can not show employee belongs departments

To fix this error, you should define a method in Employee model class, and calculate the employee belongs departments and return it’s value.

add dept emp views test case python file

Edit Employee model class source code in DjangoHelloWorld / dept_emp / file and add method get_dept_values.

def get_dept_values(self):

    ret = ''


    # 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.

Now you can call Employee model class’s get_dept_values method in html template page.

django project app dept_emp source files structure
Edit DjangoHelloWorld / templates / dept_emp / emp_list.html page like below. Please note we call {{ emp.get_dept_values }} in template page directly.

 {% for emp in emp_list %}
     <td><input type="checkbox" id="emp_{{ }}" name="emp_{{ }}"></td>
     <td>{{ }}</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>
{% endfor %}

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

Now run the example and add one employee and two department follow below steps.

  1. Open a terminal and go to the DjangoHelloWorld Django project root folder.
  2. Run $ python3 shell command to open django project shell console.
  3. Then run below code to add two exist department to exist employee jerry.
    $ python3 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')
    <Employee: jerry,100000,13901234567>
    # get the first department.
    dept_1 = Department.objects.get(id=1)
    <Department: Develop,Develop web site use Python Django>
    # get the second department
    dept_2 = Department.objects.get(id=2)
    <Department: Quality Assurance,Responsible for company website quality and test.>
    # add the two departments to the employee's departments.
    # save the employee object to save the two added department that jerry belongs to.
  4. Now start the django project server and browse url, you can see jerry belongs two departments in the employee list page like below.
    employee list page show employee belongs multiple departments

5 1 vote
Article Rating
Notify of

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

1 Comment
Oldest Most Voted
Inline Feedbacks
View all comments

Excelent!!!! Thank u so much !!! Great tutorial!

Would love your thoughts, please comment.x