MysticCodes
MysticCodes

Reputation: 3282

How can I convert django queryset list into dictionary?

I have more then two django querysets and merged them into a list as shown output below.

work_queryset = Work.objects.filter(base_id = q).values('worktype', 'datestart', 'dateend', 'dailyworktime', 'remarks')
holiday_queryset = Holiday.objects.filter(base_id = q).values('holiday_type', 'datestart', 'dateend', 'remarks')

Merged list

merged_list = list(chain(work_queryset, holiday_queryset))

output

[{'datestart': u'2016-04-11', 'dateend': u'2018-07-21', 'remarks': u'Hello remarks', 'worktype': u'Remote'}, {'remarks': u'New holiday', 'datestart': u'2018-09-22', 'dateend': u'2019-09-22', 'holiday_type': u'Sick leave'}, {'remarks': u'nothing comment', 'datestart': u'2016-04-11', 'dateend': u'2016-07-20', 'holiday_type': u'Summer holiday'}]

What i am trying to achieve is to convert merged_list into dictionary as shown below:

[{'work' : [{'datestart': u'2016-04-11', 'dateend': u'2018-07-21', 'remarks': u'Hello remarks', 'worktype': u'Remote'}], 'holiday': [{'remarks': u'New holiday', 'datestart': u'2018-09-22', 'dateend': u'2019-09-22', 'holiday_type': u'Sick leave'}, {'remarks': u'nothing comment', 'datestart': u'2016-04-11', 'dateend': u'2016-07-20', 'holiday_type': u'Summer holiday'}]}]

How can i achieve this?

Upvotes: 0

Views: 3217

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31270

I don't understand what the out list in what you're trying to achieve is for.

Seems to me you simply want

{
     'work': list(work_queryset),
     'holiday': list(holiday_queryset)
}

Upvotes: 2

Related Questions