如何獲得項目的排序查詢集以按字母順序顯示各部門中的團隊還按字母順序顯示部門?Django查詢集 - 排序兩次
簡單的模型是這樣的...
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)
'(「名」, 'dept')' – Sayse