为Django中现有条目上的ForeignKey字段提供默认值 [英] Provide a default for ForeignKey field on existing entries in Django
问题描述
我有这个模型:
class Movie(models.Model):
# here are some fields for this model
我在其中添加了以下字段(数据库已经装有电影模型): / p>
to which I added the following field (the database was already populated with Movie models):
user = models.ForeignKey(User, default=1)
我先运行了命令'makemigrations',然后又执行了'migrate':
I ran the commands 'makemigrations' and then 'migrate':
python manage.py makemigrations myapp
python manage.py migrate
但它没有工作。我想做的是将 user字段添加到Movie对象中,并为数据库中所有现有的Movie对象为其提供默认值(在这种情况下,默认值为id = 1的User对象)。
我尝试的另一件事是不使用默认值,然后在运行 makemigrations命令时将其设置为默认值1(通过选择立即提供一次性默认值选项) )。在这两种情况下,当我运行 migrate命令时,都会收到一个IntegrityError:
but it doesn't work. What I want to do is to add the 'user' field to Movie objects and provide a default for it for all the existing Movie objects in my database (in this case the default is the User object with id=1).
Another thing that I tried is to leave it without the default value and then, when i run the 'makemigrations' command, to give it the default value 1 (by selecting the "provide a one-off default now" option). In both cases, when I run the 'migrate' command I get an IntegrityError:
django.db.utils.IntegrityError: movies_movie__new.user_id may not be NULL
我还检查了数据库中已经存在的Users的ID,确保存在id = 1的用户并且确实存在。那为什么不起作用呢?谢谢。
I also checked the ids for the Users that are already in the database to make sure that a User with id=1 exists and it does. So why doesn't it work? Thank you.
推荐答案
如果添加 null = True,则可以:
If you add "null=True" it works:
user = models.ForeignKey(User, default=1, null=True)
然后
python manage.py makemigrations movies
Migrations for 'movies':
0003_auto_20150316_0959.py:
...
- Add field user to Movie
...
然后
python manage.py migrate movies
数据库应如下所示:
id|user_id|name
1|1|movie_name
2|1|movie_2
3|1|movie_3
...
所有空的user_ids的值为1。因此,您就完成了。
All the empty user_ids get a value of 1. So you're done.
现在,如果您需要将该字段设为必填字段,只需将模型更改回
Now, if you need to make that field required, just change the model back to
user = models.ForeignKey(User, default=1)
再次迁移
并再次迁移
make another migration and migrate again
这一次它将起作用,因为所有字段都具有user_id。
This time it will work since all fields have user_id.
;-)
这篇关于为Django中现有条目上的ForeignKey字段提供默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!