Django related_name not found

前端 未结 1 1983
醉话见心
醉话见心 2021-01-19 05:39

I have this model:

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


        
相关标签:
1条回答
  • 2021-01-19 06:09

    To use related_name with recursive many-to-many you need set symmetrical=False. Without it Django will not add employees attribute to the class. From the 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.

    So you can add symmetrical=False to the field:

    employers = models.ManyToManyField('self', blank=True, related_name='employees', symmetrical=False)
    
    person.employees.all() # will work now
    

    or just use employers attribute:

    person.employers.all()
    
    0 讨论(0)
提交回复
热议问题