У меня есть следующий результат QuerySet в виде списка:
<QuerySet [{'answer__question__focus': 'hearing_about_the_event', 'name': 'Facebook', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'hearing_about_the_event', 'name': 'Instagram', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'hearing_about_the_event', 'name': 'friends', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'missing_event_information', 'name': 'Line-up', 'count': 2, 'total_salience': 2.0}, {'answer__question__focus': 'missing_event_information', 'name': 'food', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'reason_for_attending', 'name': 'girlfriend', 'count': 1, 'total_salience': 1.0}, {'answer__question__focus': 'type_of_people_attending', 'name': 'incomes', 'count': 3, 'total_salience': 2.26287645101547}, {'answer__question__focus': 'type_of_people_attending', 'name': 'people', 'count': 1, 'total_salience': 1.0}]>
Теперь я пытаюсь сгруппировать этот результат в моем приложении Django по answer__question__focus с Python. Однако я изо всех сил пытаюсь получить свои данные в правильном порядке / формате. Кто-нибудь знает, как сделать это эффективно?
[
'hearing_about_the_event': # question.pk
[
{
'name': 'Leonardo Di Caprio',
'count': 4,
'salience': 3.434
},
{
'name': 'titanic',
'count': 5,
'salience': 1.12
},
{
'name': 'music',
'count': 3,
'salience': 1.12
}
],
'missing_event_information': # question.pk
[
{
'name': 'Leonardo Di Caprio',
'count': 5,
'salience': 1.5
},
{
'name': 'titanic',
'count': 4,
'salience': 1.12
},
{
'name': 'music',
'count': 2,
'salience': 1.12
}
]
]
Вот мое решение. Благодаря @Julien Kieffer
d = defaultdict(list)
for entity in entities:
question_focus = entity.pop("answer__question__focus")
d[question_focus].append(entity)