Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django convert list of objects to list of primary keys

Tags:

django

As the title says I have a list of Django objects and I want to get a list of primary keys. What is the best way of doing this?

I know I could do

my_list = []
for item in object_list:
    my_list.append(item.pk)

but was wondering if there is Django or Python specific way of doing this better.

Thanks

like image 483
John Avatar asked May 06 '10 10:05

John


1 Answers

One more pythonic way to start with is:

my_list = [item.pk for item in object_list]

A full django way:

my_list = object_list.values_list('id', flat=True)
like image 165
KillianDS Avatar answered Nov 15 '22 08:11

KillianDS