简体   繁体   中英

Django create a dict with values of a model field as key and model instance as value

I have a model Quest and it has a field type . I want to have a dict that maps type to a list of Quest . My current way of doing it is just iterating over all the Quest objects and append them to the list.

from collections import defaultdict

quests = Quest.objects.all()
dictionary = defaultdict(list)
for quest in quests:
    dictionary[quest.type].append(quest)

I am wondering if Django QuerySet has a better way to do it. I looked up aggregation() , value_list() and values() but they don't seem to achieve what I want to do.

I am not aware of any such django QuerySet functionality. You could, however, use the query to already order your quests by type so that you can use itertools.groupby in a dict comprehension without having to sort in 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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM