使用查询集中的列表值有效地创建字典

时间:2017-06-14 20:42:18

标签: python django performance loops dictionary

给定从查询集返回的一组对象,如何构造一个字典,其中一个对象属性作为键,而对象本身作为值?

当前代码:

questions = Questions.objects.all()
parent_question = defaultdict(list)
section_question = defaultdict(list)

for question in questions:
    parent_question[question.parent_id].append(question)
    section_question[question.section_id].append(question)

我可以通过移除循环以某种方式提高效率吗?使用地图还是什么?或者可能修改查询?或者我必须忍受这个?

0 个答案:

没有答案
相关问题