Reputation: 98796
I’ve got a Django model (ModelA
) with a ManyToManyField
linking to another model (ModelB
).
I’d like to write a query that selects all instances of Model A that are related to a specific set of instances from Model B.
I’d kind of like to do it like this:
related_set = ModelB.objects.filter(id__in=(1,2))
ModelA.objects.filter(modelb_set=related_set)
But that seems to select Model A instances that are related to instances 1 or 2 in Model B.
I want to select Model A instances that:
Upvotes: 2
Views: 133
Reputation: 98796
After some help from DrTyrsa, I think I’ve got it:
model_b_1 = ModelB.objects.get(id=1)
model_b_2 = ModelB.objects.get(id=2)
model_b_other = ModelB.objects.exclude(id__in(1, 2))
# Select Model A instances that are related to Model B instances 1 AND 2:
related_to_1_and_2 = ModelA.objects.filter(modelb=model_b_1).filter(modelb=model_b_2)
# Then exclude Model A instances that are related to any other Model B instances
ONLY_related_to_1_and_2 = related_to_1_and_2.exclude(modelb__in=model_b_other)
Upvotes: 1