2017-05-31 108 views
0

我有這些模型:Django的查詢集與多個M2M領域

class Doctor(models.Model): 
    coopsort = ManyToManyField('Cooperation', related_name='coopsort') 
    name = models.CharField(...) 

class Cooperation(models.Model): 
    doctor = models.ManyToManyField(Doctor, blank=True, verbose_name=u"Doc") 

我如何查詢使用coopsort M2M領域的醫生給出的所有項目合作?

Cooperation.objects.filter... <pls advise here> 
+0

爲什麼你需要在這兩個模型manytomany? –

+0

都有不同的功能原因。 – caliph

回答

0

比我預想的要容易得多。這工作對我來說:

doC# Doctor instance 
SelectedCooperations = doc.coopsort.all() 
0

在兩種模型中都不需要定義ManyToManyField。如果你需要在Doctor模式:

class Doctor(models.Model): 
    coopsort = ManyToManyField('Cooperation', related_name='coopsort') 
    name = models.CharField(...) 

class Cooperation(models.Model): 
    cooperation_name = ... 

那麼你可以像這樣過濾cooperations:由醫生名字

由醫生ID

cooperations = Cooperation.objects.filter(doctor__id=1) 

cooperations = Cooperation.objects.filter(doctor__name='John') 
+0

謝謝,但我需要在醫生模型上使用m2m字段的查詢結構。 – caliph

+0

@caliph我編輯了答案 – doru

0
doC# Doctor instance 
queryset1 = doc.coopsort.all() 
queryset2 = Cooperation.objects.filter(doctor=doc).all() 
queryset = queryset1 | queryset2 

related_name無法在m2m中工作