问题描述
我有这个模型:
class Person(models.Model):
something ...
employers = models.ManyToManyField('self', blank=True, related_name='employees')
当我执行person.employees.all()
时,出现此错误:'Person' object has no attribute 'employees'
.仅当存在实际链接时才创建相关名称.如果是,该如何检查?
When I do person.employees.all()
I get this error: 'Person' object has no attribute 'employees'
. Is the related name only created when there is an actual link in place. If yes, how can I check this?
我知道hasattr()
函数.我仍然想知道为什么在没有相关对象的情况下该属性为什么不返回空列表.
I'm aware of the hasattr()
function. I'm still wondering why the attribute doesn't return an empty list when there's no related objects.
推荐答案
要在多对多递归中使用related_name,您需要设置symmetrical=False
.没有它,Django将不会在类中添加employees
属性.从文档中:
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:
因此您可以在字段中添加symmetrical=False
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
或仅使用employers
属性:
person.employers.all()
这篇关于找不到Django related_name的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!