Search code examples
pythondjangodjango-templatesmany-to-many

Django: list User details and Group for every User-Group (Many-To-Many) relationship in template


How to query and show User info and their Group for every User-Group (Many-To-Many) relationship in Django template?

The result should look like:

| User username | User email     | Group name  |
| ------------- | -------------- | ----------- |
| user1         | [email protected] | groupA      |
| user1         | [email protected] | groupB      |
| user2         | [email protected] | groupA      |
| user2         | [email protected] | groupC      |
| user3         | [email protected] | groupA      |

My question is similar to Vanilla Django Query to show 'flattened' User/Group (ManyToMany) Listing, but would like show more user details on the table.

I naively thought something like this would have worked, but didn't.

{% for group in groups %}
  {% for user in group.users.all %}
<tr>
    <td>{{user.username}}</td>
    <td>{{user.email}}</td>
    <td>{{group.name}}</td>
</tr>
  {% endfor %}
{% endfor %}

Using the raw SQL query has solved my problem: https://stackoverflow.com/a/38780451/991505 , but I am looking for better answers in the Django/Python way.


Solution

  • If you use Django's Group, you access the set of users with:

    {% for group in groups %}
      {% for user in group.user_set.all %}
        …
      {% endfor %}
    {% endfor %}

    You can further boost efficiency by prefetching all the related users with one extra query, so in the view you work with:

    groups = Group.objects.prefetch_related('user_set')