我有这些模特:
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 :(得分: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()