具有来自同一个表的 2 个外键的 Django 模型
我想要一个带有来自同一个表的 2 个外键的 Django 模型。 这是一个事件表,有两列员工:“参与者”和“接收者”。 但我收到这个错误:
错误:一个或多个模型未验证:tasks.task:中介 模型 TaskEvent 有多个 Employee 外键,即 含糊不清,是不允许的。
有更好的方法来建模吗?
我想我要添加一个 TaskEvent_to_Employee
表。 其中将有两条记录,一条记录对应与每个 TaskEvent
相关的两名员工。 有谁知道更简单的解决方法?
I wanted a Django model with 2 foreign keys from the same table. It's an event table which has 2 columns for employees: the 'actor' and the 'receiver'. But I get this error:
Error: One or more models did not validate: tasks.task: Intermediary
model TaskEvent has more than one foreign key to Employee, which is
ambiguous and is not permitted.
Is there a better way to model this?
I think I'm going to add a TaskEvent_to_Employee
table. There will be two records in it, one for each of the two employees related to each TaskEvent
. Does anyone know an easier workaround?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我还没有这样做,但我使用 inspectdb 从现有数据库生成 models.py 文件,该文件正是这样做的 - 这就是检查数据库返回的内容,所以它应该可以工作:
希望可以工作对你来说 - 如果不是的话我也会遇到问题。
I haven't done this yet, but I used inspectdb to generate the models.py file from an existing DB that does exactly that - this is what inspectdb threw back, so it should work:
Hope that works for you - if it doesn't I am going to have a problem too.
我认为您正在寻找的是ForeignKeyFields 上的related_name 属性。 这将允许您引用同一个表,但为关系指定 django 特殊名称。
更多信息:
I think what you're looking for is the related_name property on ForeignKeyFields. This will allow you to reference the same table, but give django special names for the relationship.
More Info:
使用 lated_name 是我的解决方案:
Using related_name was my solution:
从错误消息来看,听起来您正在尝试将两个外键放入通过
ManyToManyField
的through
参数使用的中间表上的同一对象,说明的文档:From the error message, it sounds like you're trying to put two foreign keys to the same object on an intermediary table used via the
through
argument toManyToManyField
, the documentation for which states:两列是一个表的一部分这一事实意味着这两个字段是相关的,因此单独引用它们并不理想。 模型的foreignkey应该是您引用的表的主键:
然后您将这样引用列:
如果您愿意,您还可以更改类/模型使用属性引用外部属性的方式。 在你的课堂上,你将执行以下操作:
这将允许你调用 foo.actor 和 foo.receiver 但我相信时间越长,foo.event.actor 会更加Pythonic
The fact that two columns are part of one table implies that the two fields are related, therefor to reference them individually is not ideal. The ForeignKey of your model should be the primary key of the table you are referencing:
You would then reference the columns as such:
If you wish you could also change the way your class/model references the foreign attributes with properties. In your class you would do the following:
This would allow you to then call foo.actor and foo.receiver but I believe the longer, foo.event.actor would be more pythonic