Format queryset return dictionary of primary keys?

9,614 views
Skip to first unread message

diafygi

unread,
Aug 4, 2011, 3:19:37 PM8/4/11
to Django users
Howdy all,

I'm know you can create a list of dictionaries for a queryset using
values(). However, I'm wondering if you can create one dictionary
where the keys are the primary keys of the result.

For example:

class Car(models.Model):
vin = models.IntegerField()

>>Model.objects.all().values()
[{'id' : 1, 'vin' : 189554}, {'id' : 1, 'vin' : 189555}, ...]

Is there a built in way to get:
>>Model.objects.all().something_pk_values()
{1 : {'vin':189554}, 2 : {'vin':189555}}

Thanks!

Daniel

Shawn Milochik

unread,
Aug 4, 2011, 4:06:29 PM8/4/11
to django...@googlegroups.com
I don't know about built-in, but you could do it in Python by iterating
through your list and creating a dictionary with a key of the id and
value of the rest of the dictionary.

diafygi

unread,
Aug 4, 2011, 4:08:59 PM8/4/11
to Django users
Right, that's what I'm currently doing. I was just wondering if there
was a pre-defined way.

Javier Guerra Giraldez

unread,
Aug 4, 2011, 4:12:31 PM8/4/11
to django...@googlegroups.com
On Thu, Aug 4, 2011 at 2:19 PM, diafygi <dia...@gmail.com> wrote:
> Is there a built in way to get:
>>>Model.objects.all().something_pk_values()
> {1 : {'vin':189554}, 2 : {'vin':189555}}


built in to Python:

dict ((o.pk, o) for o in Model.objecs.all())

--
Javier

MM

unread,
Jan 14, 2020, 5:33:44 PM1/14/20
to Django users
or:

o.pk: o for o in Model.objecs.all() }
Reply all
Reply to author
Forward
0 new messages