具有多个m2m字段的Django查询集

时间:2017-05-31 09:39:47

标签: django django-models django-queryset

我有这些模特:

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>

3 个答案:

答案 0 :(得分: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')

答案 1 :(得分:0)

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

related_name无法在m2m中运行

答案 2 :(得分:0)

比我想象的要容易得多。这对我有用:

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