2016-11-28 99 views
0

如何獲得項目的排序查詢集以按字母順序顯示各部門中的團隊還按字母順序顯示部門?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) 
+1

'(「名」, 'dept')' – Sayse

回答

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}) 
+1

我會建議進行以下編輯:檢索球隊,比如'teams_ = Teams.objects.order_by('dept','name')。annotate(team_count = Count('projects'))',接下來是' team_list = [(x,x.team_count)for x in teams_]'。這樣你可以在一個查詢中得到它。 –