Django / python如何从对象列表中获取id的列表 [英] Django/python How to get a list of id's from a list of Objects
问题描述
如果我有一些查询列表(在这种情况下是Django模型)。
If I have a list of objects acquired by some query (in this case Django models).
friends = Friend.objects.friends(user1)
如何获取ids列表,所以我可以使用它搜索另一个模型,如下所示:
How can I get the list of ids, so I can use it to search another model, like this:
items = Item.objects.get(pk__in=friends_ids).order_by('date')
我很确定lambda表达式应该能够做到,但我无法想象
I'm pretty sure the lambda expressions should be able to do it but I can't figure it out...
推荐答案
如果朋友的返回值
是 QuerySet
对象,可以使用 QuerySet.values_list
方法:
If the return value of the friends
method is a QuerySet
object, you can use QuerySet.values_list
method:
friends_ids = friends.values_list('id', flat=True)
如果它不是一个 QuerySet
对象,可以使用 list comprehension (这可以用于 QuerySet
和非QuerySet一):
If it's not a QuerySet
object, you can use list comprehension (This one can be used for both QuerySet
and non-QuerySet one):
friends_ids = [friend.id for friend in friends]
这篇关于Django / python如何从对象列表中获取id的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!