2017-02-04 104 views
2

我有這樣的模式:Django的related_name沒有找到

class Person(models.Model): 
    something ... 
    employers = models.ManyToManyField('self', blank=True, related_name='employees') 

當我做person.employees.all()我得到這個錯誤:'Person' object has no attribute 'employees'。相關名稱僅在實際鏈接到位時才創建。如果是的話,我該如何檢查?

編輯:我知道hasattr()函數。我仍然想知道爲什麼該屬性在沒有相關對象時不返回空列表。

回答

3

要使用related_name與遞歸多對多,您需要設置symmetrical=False。沒有它,Django不會爲該類添加employees屬性。從docs

When Django processes this model, it identifies that it has a ManyToManyField on itself, and as a result, it doesn’t add a person_set attribute to the Person class. Instead, the ManyToManyField is assumed to be symmetrical – that is, if I am your friend, then you are my friend.

所以,你可以添加symmetrical=False到外地:

employers = models.ManyToManyField('self', blank=True, related_name='employees', symmetrical=False) 

person.employees.all() # will work now 

或只使用employers屬性:

person.employers.all() 
+1

感謝一大堆! – rwms