两个ManyToMany通过Django中的相同中间模型与同一模型的关系

时间:2017-04-21 22:46:39

标签: django django-models django-1.11

我的模特:

class Person(SchoolModel):
    first_name = models.CharField(max_length=75)
    last_surname = models.CharField(max_length=75)

    students = models.ManyToManyField('self', through='StudentParent',
        through_fields=('parent', 'student'), related_name='+')
    parents = models.ManyToManyField('self', through='StudentParent',
        through_fields=('student', 'parent'), related_name='+')


class StudentParent(SchoolModel):
    student = models.ForeignKey('Person')
    parent = models.ForeignKey('Person')
    relation = models.CharField(max_length=26)

    class Meta:
        unique_together = ('student', 'parent')

如上所示,人物模型与自身有两个m2m关系:学生和父母。每个人可能在同一个人桌上有许多学生,也有许多父母。

但是,Django不允许这样做:

Person: (models.E003) The model has two many-to-many relations through  
the intermediate model 'StudentParent'.

我不明白为什么Django拒绝这样做,特别是因为它没有使用自定义中间表保存或验证m2m字段。另一方面,我只需要使用这些字段来更轻松地检索相关模型。例子:

person_obj.students.all()
Person.objects.filter(parents__in=another_person_queryset)

所以我的问题是,1)在Django1.11中有没有解决这个问题的方法(通过配置等可以实现这样的2 m2m字段)? 2)有没有办法通过其他方式实现只读方案?

使用代理中介模型欺骗django使1)发生? 使用自定义管理器有助于实现2)吗?什么是最短,最好的道路?

注意:我知道之前有一个类似的question,但是这有点不同而且有点旧。

1 个答案:

答案 0 :(得分:1)

似乎通过代理模型欺骗Django的目的是为了我上面描述的目的(检索模型实例的相关数据或在过滤查询集中)。所以模型成为:

class Person(SchoolModel):
    first_name = models.CharField(max_length=75)
    last_surname = models.CharField(max_length=75)

    students = models.ManyToManyField('self', through='StudentParentProxy', # << !!!!!!
        through_fields=('parent', 'student'), related_name='+')
    parents = models.ManyToManyField('self', through='StudentParent',
        through_fields=('student', 'parent'), related_name='+')


class StudentParent(SchoolModel):
    student = models.ForeignKey('Person')
    parent = models.ForeignKey('Person')
    relation = models.CharField(max_length=26)

    class Meta:
        unique_together = ('student', 'parent')


class StudentParentProxy(StudentParent):
    class Meta:
        proxy = True  # << !!!!!!
相关问题