Django查询集 - 排序两次

时间:2016-11-28 11:01:44

标签: python django sorting

如何获取Projects的排序查询集,以按字母顺序显示每个部门中的团队按字母顺序显示部门?

Símple模型就是这样......

class Department(models.Model):
    name = models.CharField(max_length=50)

class Teams(models.Model):
    name = models.CharField(max_length=50)
    dept = models.ForeignKeyField(Department, on_delete=CASCADE)

    class Meta:
        ordering = ('name',)

class Project(models.Model):
    name = models.CharField(max_length=50)
    team = models.ForeignKeyField(Teams, on_delete=CASCADE)

在Views.py中,我希望收集各个团队,并按部门按字母顺序显示每个团队的项目数量。

...
team_list = []
teams_ = Teams.objects.all().order_by('dept__name')
for team in teams_:
    projects = Project.objects.all(team=team)
    team_list.append((team, len(projects)))
return render(request, 'index.html', {'team_list': team_list})

然后在模板中......

<ul>
{% for team, len in team_list %}
<li><a href="{% url 'team_detail' team.id %}">{{ team.dept.name|upper }} - {{ team.name|capfirst }} ({{ len }})</a></li>
{% endfor %}
</ul>

显示如下内容......

Archive - Backup (22)
Archive - Archive (3)
Support - Glossary (32)
Support - A Team (12)
Support - Members (22)

哪个不正确 - 我想要一个有这样的部门和团队的有序字母列表......

Archive - Archive (3)
Archive - Backup (22)    
Support - A Team (12)
Support - Glossary (32)
Support - Members (22)

1 个答案:

答案 0 :(得分:3)

您不需要使用 Teams.objects.all(),只需将order_by同样正常工作:然后按这些字段排序,使用单独的逗号,如下所示:

team_list = []
teams_ = Teams.objects.order_by('dept','name')
for team in teams_:
    projects = Project.objects.all(team=team)
    team_list.append((team, len(projects)))
return render(request, 'index.html', {'team_list': team_list})