2011-12-05 82 views
2

我有一個Django模型(ModelA),其中ManyToManyField鏈接到另一個模型(ModelB)。如何過濾Django模型中的對象(ManyToMany)與另一個模型中特定的一組對象相關?

我想寫的是選擇那些與實例從模型B

組特定我想那種喜歡做這樣的A型的所有實例的查詢:

related_set = ModelB.objects.filter(id__in=(1,2)) 
ModelA.objects.filter(modelb_set=related_set) 

,但似乎選擇

我想選擇A型實例使用有關實例1 2模型B模型的實例是:

  1. 是模型B實例1 2有關;
  2. 與任何其他模型B實例無關。

回答

1

some help from 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) 
+0

是的,愚蠢的錯誤。 :-)如果你想添加幾個條件,你可以使用'reduce'用'filter'方法,或者用[Q objects](https://docs.djangoproject.com/en/dev/topics/db/queries/#複雜的查找與 - q-對象)。我只是使用字典將是最優雅的,但沒有運氣。 :-)我刪除了我的答案。 – DrTyrsa

+0

當然 - 如果它可以採取任意數量的條件,這通常會更有用。非常感謝您的幫助,但它確實指出了我的正確方向。 –

相關問題