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...
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.
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?
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With