我想以一种方式查询数据库,而不是仅按某个字段排序,而是为该字段的每个唯一值获取一个单独的QuerySet(或字典,列表等)。希望以下示例可以帮助您:

假设一个模型像

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

调用Person.objects.all()。order_by('last_name')给我一个长的QuerySet。我希望每个唯一的last_name都有一个单独的列表。因此,每个具有last_name =“Smith”的人的列表,以及每个具有last_name =“Nguyen”的人的列表,等等。

显然,我无法提前知道数据库中将有哪些last_name,也无法知道会有多少人共享一个通用的last_name。是否有任何快速,高效或自动的方式在django中做到这一点,还是我只需要在收回一个大查询集后自己处理数据?

最佳答案

您可以获得所有唯一的姓氏:

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

丹尼尔·罗斯曼(Daniel-Roseman)是对的,它效率很低,因此这里有一个调整版本...
from collections import defaultdict
values = defaultdict(list)
_ = map(lambda person: values[person.last_name].append(person), Person.objects.all())

请注意_ = ...是这样,因此我们不会在终端上打印所有的None;)

关于python - 拆分查询集或按字段获取多个查询集,而不仅仅是按字段排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11388296/

10-11 06:18
查看更多