找不到Django related_name [英] Django related_name not found

查看:129
本文介绍了找不到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'.仅当存在实际链接时才创建相关名称.如果是,该如何检查?

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:

当Django处理此模型时,它会确定自己具有一个ManyToManyField,因此,它不会向Person类添加person_set属性.相反,假定ManyToManyField是对称的-也就是说,如果我是您的朋友,那么您就是我的朋友.

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

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆