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?
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.
I want to get a filtered object with several id’s that I will specify:
TestQuestionBlok.objects.filter()
How to write this filter?
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.