在Django模式中,related_name参数无法正常工作? [英] related_name argument not working as expected in Django model?

查看:544
本文介绍了在Django模式中,related_name参数无法正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近在我的Django模型中遇到了一个ForeignKey冲突。我需要有两个外键(所有者,assigned_to)最终指向同一个模型(用户)。



根据我的理解,我需要一个 related_name 参数来解决这个问题。所以我这样做:

  assigned_to = models.ForeignKey(TaskUser,blank = True,null = True,related_name ='user_assignment' )

 code> owner = models.ForeignKey(TaskUser,related_name =user_ownership

m仍然得到错误:

  tasks.task:字段所有者的访问者与相关字段TaskUser.user 
_ownership'在owner的定义中添加一个related_name参数
tasks.task:字段'owner'的反向查询名称与相关字段'TaskUser.user_ownership'冲突。将相关名称参数添加到定义中对于'所有者'

为什么我仍然收到此错误?



有一个catch,所有者在一个超类(BaseWidget)中,而 assigned_to 是在一个子类(任务)中。在继承中使用 related_name 是否存在问题nce关系?我需要覆盖所有者的继承,并重新定义子类中的 related_name ?我会感谢任何帮助!

解决方案

如果你有 ForeignKey 在抽象基类中,继承自它的每个类都将具有这种关系。因此,您不得对其 related_name 进行硬编码,因为所有子类都将尝试在实际类上创建相同的访问器( TaskUser在这种情况下)。



您应该更好地执行以下操作:

  owner = models。 ForeignKey(TaskUser,related_name =%(app_label)s _%(class)s_ownership)

django docs


I recently got a ForeignKey clash in my Django model. I have the need to have two foreign keys (owner, assigned_to) ultimately pointing to the same model (a user).

From what I understand I need a related_name argument to solve that problem. So I did that:

assigned_to = models.ForeignKey(TaskUser, blank=True, null=True, related_name='user_assignment')

and

owner = models.ForeignKey(TaskUser, related_name="user_ownership"

But I'm still getting an error:

tasks.task: Accessor for field 'owner' clashes with related field 'TaskUser.user
_ownership'. Add a related_name argument to the definition for 'owner'.
tasks.task: Reverse query name for field 'owner' clashes with related field 'TaskUser.user_ownership'. Add a related_name argument to the definition for 'owner'.

Why am I still getting this error?

There is one catch, owner is in a super class (BaseWidget) and assigned_to is in a sub class (Task). Are there issues with using related_name in an inheritance relationship? Do I need to just override the inheritance of owner and redefine related_name in the sub class instead? I'd appreciate any help!

解决方案

If you have ForeignKey relationships in an abstract base class every class inheriting from it will have this relationship. As a result of this you must not 'hardcode' its related_name, because all sub classes will try to create the same accessor on the realted class (TaskUser in this case).

You should better do something like:

owner = models.ForeignKey(TaskUser, related_name="%(app_label)s_%(class)s_ownership")

See the django docs on this.

这篇关于在Django模式中,related_name参数无法正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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