Django / python How to get a list of identifiers from a list of objects

If I have a list of objects received by some request (in this case, Django models).

friends = Friend.objects.friends(user1)

How can I get a list of identifiers, so I can use it to search for another model, for example:

items = Item.objects.get(pk__in=friends_ids).order_by('date')

I'm sure lambda expressions should be able to do this, but I can't figure it out ...

+4
source share
1 answer

If the return value of the method friendsis an object QuerySet, you can use the QuerySet.values_listmethod:

friends_ids = friends.values_list('id', flat=True)

QuerySet, ( QuerySet QuerySet):

friends_ids = [friend.id for friend in friends]
+7

Source: https://habr.com/ru/post/1568962/


All Articles