如何从Django模型中过滤与另一个模型中的特定对象集相关的对象(ManyToMany) ?

时间:2022-09-24 23:12:50

I’ve got a Django model (ModelA) with a ManyToManyField linking to another model (ModelB).

我有一个Django模型(ModelA),其中有许多tomanyfield链接到另一个模型(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.

我想编写一个查询,该查询选择与模型B中特定的一组实例相关的模型a的所有实例。

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.

但这似乎选择了与模型B中的实例1或2相关的模型A实例。

I want to select Model A instances that:

我想选择模型A实例:

  1. are related to Model B instances 1 and 2;
  2. 与模型B实例1和2相关;
  3. are not related to any other Model B instances.
  4. 不与任何其他模型B实例相关。

1 个解决方案

#1


1  

After some help from DrTyrsa, I think I’ve got it:

在DrTyrsa的帮助下,我想我得到了:

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)

#1


1  

After some help from DrTyrsa, I think I’ve got it:

在DrTyrsa的帮助下,我想我得到了:

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)