Django 创建一个字典,模型字段的值作为键,模型实例作为值
Django create a dict with values of a model field as key and model instance as value
我有一个模型 Quest
,它有一个字段 type
。我想要一个将 type
映射到 Quest
列表的字典。我目前的做法是遍历所有 Quest
对象并将它们附加到列表中。
from collections import defaultdict
quests = Quest.objects.all()
dictionary = defaultdict(list)
for quest in quests:
dictionary[quest.type].append(quest)
我想知道 Django QuerySet
是否有更好的方法。我查了 aggregation()
、value_list()
和 values()
,但他们似乎没有实现我想做的事情。
我不知道在 dict
理解中有任何这样的 django QuerySet
functionality. You could, however, use the query to already order your quests by type
so that you can use itertools.groupby
而不必在 Python 中排序:
from itertools import groupby
quests = Quest.objects.all().order_by('type')
dictionary = {k: list(g) for k, g in groupby(quests, key=lambda q: q.type)}
我有一个模型 Quest
,它有一个字段 type
。我想要一个将 type
映射到 Quest
列表的字典。我目前的做法是遍历所有 Quest
对象并将它们附加到列表中。
from collections import defaultdict
quests = Quest.objects.all()
dictionary = defaultdict(list)
for quest in quests:
dictionary[quest.type].append(quest)
我想知道 Django QuerySet
是否有更好的方法。我查了 aggregation()
、value_list()
和 values()
,但他们似乎没有实现我想做的事情。
我不知道在 dict
理解中有任何这样的 django QuerySet
functionality. You could, however, use the query to already order your quests by type
so that you can use itertools.groupby
而不必在 Python 中排序:
from itertools import groupby
quests = Quest.objects.all().order_by('type')
dictionary = {k: list(g) for k, g in groupby(quests, key=lambda q: q.type)}