Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django/python How to get a list of id's from a list of Objects

If I have a list of objects acquired by some query (in this case Django models).

friends = Friend.objects.friends(user1)

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

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

like image 316
Tim Avatar asked Dec 25 '14 14:12

Tim


People also ask

How to filter a list of values in Django?

Django has special __in operator that we can use with Django filter () method. This will return query set from the model “Contact” after filtering a Django query with a list of values. You can also write a query to exclude the filter object which has an id present in the list.

How to exclude a list of contacts in Django queryset?

You can also write a query to exclude the filter object which has an id present in the list. For this, we are using exclude () method. This will return all the contacts excluding which has an id not in the list. How to Sort Django QuerySet?

How to exclude the filter object with ID present in list?

You can also write a query to exclude the filter object which has an id present in the list. For this, we are using exclude () method.

How to get a list of objects with the same foreign key?

In general, is there a better way to get a list of objects that have the same foreign key? You can specify a related_name for the company foreign key on your Interview model like so.


1 Answers

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)

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]
like image 80
falsetru Avatar answered Sep 28 '22 23:09

falsetru