简体   繁体   English

在 Django ORM 中修改现有 model 的外键

[英]Modifying the foreign key of an existing model in the Django ORM

I have a model which has a ForeignKey field, and I wish to change its value in a model instance, I tried something like this:我有一个 model ,它有一个 ForeignKey 字段,我希望在 model 实例中更改它的值,我尝试了这样的事情:

#object and user are model instances, owner is a FK field
object.owner = user

This raises a ValueError: "object.owner is not an instance of User"这会引发 ValueError:“object.owner 不是 User 的实例”

Is there a workaround for this?有解决方法吗?

user should be a correct instance of User, and if you just created it instead of retrieved it from the database, it should be save()-d before you save object. user 应该是 User 的正确实例,并且如果您只是创建它而不是从数据库中检索它,则它应该在保存 object 之前进行 save()-d。

Make sure that user is an instance of the same User that was used in defining the ForeignKey.确保user是用于定义外键的同一User的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM