17

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...

1 Answer 1

36

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]
Sign up to request clarification or add additional context in comments.

1 Comment

It returns a list, no queryset. Good point in using the list comprehension... I was thinking way to complex and completely forgot about such an easy solution :).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.