如何在 Django 模板中迭代查询集

How do I iterate inside a queryset in django template

我的 django 视图 returns 字典 people 包含列表格式的所有键的值。 视图的代码是:

class ProjectDetail(View):
    def get(self, request, pk, *args, **kwargs):
        project = Project.objects.get(pk=pk)
        roles = Role.objects.filter(project=pk)
        people = {}
        for role in roles:
            try:
                people[role] += Person.objects.filter(role=role.pk)
            except KeyError:
                people[role] = [Person.objects.filter(role=role.pk)]

        context = {
            'project': project,
            'people': people
        }

        return render(request, 'project_management/project_detail.html', context)

我的模特

class Project(models.Model):
    title = models.CharField(max_length=2000)
    introduction = models.TextField(blank=True)

class Role(models.Model):
    role_name =  models.CharField(max_length=30)
    project = models.ForeignKey(Status, on_delete=models.CASCADE)

class Person(models.Model):
    name = models.CharField(max_length=30, blank=True, null=True)
    role = models.ForeignKey(Role, on_delete=models.CASCADE)

为了遍历我使用的字典:

{% for designation, persons in people.items %}
<h5> {{ designation.role_name }} </h5>
<ul>
    {% for person in persons %} <!-- My Problem lies here, this loop is not iterating, it's running only once-->
        <li> {{person}} </li>
    {% endfor %}
</ul>
{% endfor %}

我得到的结果是:

我希望单独列出查询集中的项目,而不是显示在方括号内。我怎样才能做到这一点?

您不需要完成所有这些工作。您只能传递 project。例如:

from django.shortcuts import get_object_or_404

class ProjectDetail(View):
    def get(self, request, pk, *args, **kwargs):
        project = get_object_or_404(Project, pk=pk)
        return render(request, 'project_management/project_detail.html', {'project': project})

或更简单 DetailView [Django-doc]:

class ProjectDetail(DetailView):
    queryset = Status.objects.prefetch_related(
        'role_set', 'role_set__person_set'
    )
    template_name = 'project_management/project_detail.html'
    context_object_name = 'project'

然后在模板中你可以渲染它:

{% for role in project.role_set.all %}
<h5> {{ role.role_name }} </h5>
<ul>
    {% for person in role.person_set.all %}
        <li> {{ person.name }} </li>
    {% endfor %}
</ul>
{% endfor %}