Django与递归M2M关系的逆向关系

时间:2017-01-16 19:44:35

标签: django django-models python-3.5 django-1.10

尝试从此处的文档进行扩展:https://docs.djangoproject.com/en/1.10/topics/db/models/#extra-fields-on-many-to-many-relationships

上下文使人们更容易理解,Person对象,M2M与自身的关系定义了两个人之间的“关系类型”,如父/子/订婚

我的Models.py:

RELATIONSHIPS = (

    (0, 'Child'),
    (1, 'Parent'),
    (2, 'Engaged'),
)

class Person(models.Model):
    code = models.AutoField(primary_key=True, verbose_name="Person Code")
    name = models.CharField(max_length=150, blank=True, null=True, verbose_name="Name")

    relationships = models.ManyToManyField(
        'self', 
        through = 'Person_Person', #This lets you define the model that will act as an intermadiary
        symmetrical = False, #This needs to be set with recursive relationships
        )

class Person_Person(models.Model):
    person_1 = models.ForeignKey('Person', on_delete=models.CASCADE, 
        related_name='%(class)s_person_1', verbose_name="Person 1")
    person_2 = models.ForeignKey('Person', on_delete=models.CASCADE,
        related_name='%(class)s_person_2', verbose_name="Person 2")
    relationship_type = models.IntegerField(choices = RELATIONSHIPS, default = 5, verbose_name="Relation")

测试代码:

p1 = Person.objects.create(name = 'Man')
p2 = Person.objects.create(name = 'Woman')

relation = Person_Person(person_1 = p1, person_2 = p2, relationship_type = 2)
reation.save()

print(p1.relationships.all(), p2.relationships.all())
#>><QuerySet [<Person: 108 Woman>]>
#>><QuerySet []>

现在针对这个问题,p2关系字段的查询集返回为空,我理解为什么当你考虑非递归关系时,但在这种情况下调用p2.relationships_set没有意义,即使它确实如此,我怎么知道Person是关系的person_1person_2

欢迎任何建议

1 个答案:

答案 0 :(得分:1)

这似乎是重复的 How to make recursive ManyToManyField relationships that have extra fields symmetrical in Django? 但我不能标记他们

基本上这在django中是不可能的,因为你必须定义symmetrical=False。 您可以选择添加第二个m2m字段。另一个帖子有一些关于那个

的好读物