2012-07-09 69 views
4

我想以某種方式查詢數據庫,而不僅僅是按某個字段排序,我得到一個單獨的QuerySet(或字典,列表,無論)for該領域的每個獨特價值。希望下面的例子將幫助:按字段拆分查詢集或獲取多個查詢集,而不是按字段排序

假設像

Class Person(models.Model): 
    first_name = models.CharField() 
    last_name = models.CharField 

模型調用Person.objects.all()ORDER_BY( '姓氏')給了我一個很長的QuerySet。我想要爲每個唯一姓氏單獨列出一個列表。因此,每個人姓氏=「史密斯」和另一個名單爲每個人與last_name =「阮」等列表

顯然我不能提前知道last_names將在數據庫中,也不知道多少人們會分享一個共同的姓氏。是否有任何快速,高效或自動的方式在django中執行此操作,或者我只需要在收到一個大型查詢集後自行處理數據?

回答

0

你可以得到所有的獨特lastnames:

from django.db.models import Count 
... 
last_names = Person.objects.values('last_name').annotate(Count('last_name')) # This will return all the unique last_names 
values = dict(((last_name['last_name'], Person.objects.all().filter(last_name = last_name['last_name'])) for last_name in last_names if last_name['last_name__count'])) 
# This will create a dictionary where the keys are all the unique names and the values are querysect of all the values that have that lastname 

丹尼爾 - 羅斯曼是正確的它是相當低效所以繼承人一個調整版本...

from collections import defaultdict 
values = defaultdict(list) 
_ = map(lambda person: values[person.last_name].append(person), Person.objects.all()) 

請注意_ = ...是所以我們不打印終端上的所有None;)

3

看看regroup標籤。

{% regroup persons by last_name as surname_list %} 

<ul> 
{% for last_name in surname_list %} 
    <li>{{ last_name.grouper }} 
    <ul> 
     {% for person in last_name.list %} 
      <li>{{ person.last_name }}, {{ person.first_name }}</li> 
     {% endfor %} 
    </ul> 
    </li> 
{% endfor %} 
</ul> 

(此代碼是未經測試,請閱讀文檔和修復任何自己的問題)

+0

謝謝!這真的很有幫助。我試圖緩和一下,但是我目前缺乏聲譽得分,我會在提高聲譽後再回來。我接受下面的答案,因爲它在視圖而不是模板中完成了工作。 – Tango 2012-07-09 03:07:16

+0

我很好奇,爲什麼你認爲在視圖中進行分組比在模板上做得更好?看起來像在模板上進行分組會導致視圖中的代碼更清晰並且性能更好(請記住,django中的querysets是懶惰的)。 – 2012-07-09 03:43:24

9

薩米的代碼是正確的,但非常低效:你做N + 1查詢(其中n是獨一無二的姓氏數量)。既然你會得到表中的所有對象,那麼不妨一次完成。改爲:

from collections import defaultdict 
person_dict = defaultdict(list) 
persons = Person.objects.all() 
for person in persons: 
    person_dict[person.last_name].append(person) 
+0

+1謝謝你,你是對的。 – 2012-07-09 20:28:36

+0

這仍然會導致多個查詢+所有查詢。我是否錯過了爲什麼會發生這種情況? – Chris 2013-11-17 01:37:57