在Django中向模型添加字段而无需删除数据库。

huangapple go评论61阅读模式
英文:

Add a field to a model in Django without having to delete the database

问题

我想在Django模型中添加一个字段。但是,当我这样做时,我会收到以下错误:django.db.utils.OperationalError: no such column: . 我知道我可以通过删除数据库并运行迁移来解决这个问题,但是否有一种方法可以在不删除数据库的情况下完成?每次我想要向模型添加字段时,都需要重新放入所有数据,这是一项繁重的工作。

运行迁移并删除迁移文件不起作用。

英文:

I would like to add a field to a model in Django. However, when I do this I get the following error: django.db.utils.OperationalError: no such column: . I know I can fix this by deleting the database and running migrations, but is there a way to do it without having to delete the database? It is a lot of work to put all the data in there again every time I want to add a field to a model.

Running migrations and deleting the migration files does not work.

答案1

得分: 1

不要弄乱很多。很简单,在模型中进行任何更改后,只需运行以下命令:

python manage.py makemigrations
python manage.py migrate
英文:

Don't mess up a lot. It's easy, after any change in model just run these commands

python manage.py makemigrations
python manage.py migrate

答案2

得分: 0

如果你已经运行了以下命令 python manage.py makemigrationspython manage.py migrate,而且你错误地绕过了添加该字段的迁移文件,你可以检查你的数据库,在表 django_migrations 下,你可以删除迁移文件创建该列的记录,然后再次运行命令 python manage.py migrate

英文:

If you have runned the commands python manage.py makemigrations and
python manage.py migrate and you have mistakenly bypass the migration file that added the field, you can check your database, under the table django_migrations you can delete the record where the migration file created the column and run the command python manage.py migrate again.

答案3

得分: 0

我终于弄清楚了。我有一个依赖于CsvCreate模型的modelform,这就是为什么迁移无法运行的原因:

parameters = CsvCreate.objects.values().latest('uploaded')['parameters']

当我将其注释掉并运行迁移时,一切都正常工作。

英文:

I finally figured it out. I have a modelform that depends on the CsvCreate model, which is why the migrations would not run:

parameters = CsvCreate.objects.values().latest('uploaded')['parameters']

When I commented it out and ran the migrations everything worked.

huangapple
  • 本文由 发表于 2023年2月27日 19:07:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579679.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定