在模板中显示给定模型的ManyToManyField属性

时间:2016-07-21 09:37:44

标签: django django-templates

如何在模板中显示模型的ManyToManyField相关的属性?

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(...)

模板

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

我可以显示用户的用户名,但不能显示其他字段。

1 个答案:

答案 0 :(得分:2)

由于ManyToMany关系可能有许多对象,我所要做的就是迭代它们:

<?php echo $row['about_desc1']; ?> 

更新:正如Todor建议添加prefetch_related,以避免不必要的数据库查询

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