Django database query: how to get multiple objects by id?

Question:

I want to get a filtered object with several id’s that I will specify:

TestQuestionBlok.objects.filter()

How to write this filter?

Asked By: Vahe Hakobjanyan

||

Answers:

If you have a list of the ids, like [1, 4, 9], you can work with the __in lookup [Django-doc]:

TestQuestionBlok.objects.filter(pk__in=[1, 4, 9])

Given these ids exist (in the database), these will be in the queryset. So it will return at most three items here with the same query.

Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.