2017-01-16 138 views
0

試圖從文檔中這裏展開:https://docs.djangoproject.com/en/1.10/topics/db/models/#extra-fields-on-many-to-many-relationshipsDjango的反向關係與遞歸M2M關係

的情況下更容易理解,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的關係字段queryset返回爲空,我明白爲什麼當你考慮一個非遞歸關係時,但在這種情況下調用p2.relationships_set是沒有意義的,即使它做到了,我會如何知道Personperson_1還是person_2的關係?

任何建議,歡迎

回答