简体   繁体   中英

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:

#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"

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.

Make sure that user is an instance of the same User that was used in defining the ForeignKey.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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