开发者

django convert list of objects to list of primary keys

开发者 https://www.devze.com 2022-12-29 15:13 出处:网络
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?

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 bett开发者_JS百科er.

Thanks


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消