loar
loar

Reputation: 1745

Show ManyToManyField attributes of a given model in template

How can I show in a template the attributes related by a ManyToManyField of a model?

models.py

class Group(models.Model):
    name = models.CharField()
    user = models.ManyToManyField(User, related_name='user_group')

class Team(models.Model):
    name = models.CharField()
    group = models.ManyToManyField(Group, related_name='group_team')

views.py

class Index(ListView):
    template_name = 'App/index.html'
    model = User

    def get_queryset(self):
        return User.objects.filter(...)

template

{% for user in user_list %}
    {{ user.username }}
    {{ user.user_group.name }}
    {{ user.user_group.group_team.name }}
{% endfor %}

I can show the username of the user but not the rest of the fields.

Upvotes: 0

Views: 139

Answers (1)

loar
loar

Reputation: 1745

Since a ManyToMany relationship may have many objects all I had to do is iterate over them:

{% for group in user.user_group.all %}
    {{ group.name }}
{% endfor %}

Update: As Todor suggests adding prefetch_related avoid unnecessary database queries

User.objects.filter(...).prefetch_related('user_group')

Upvotes: 2

Related Questions