简体   繁体   English

在我向其中一个模型添加新字段后,无法迁移到 django 应用程序

[英]Can't make migrations to django app after i added a new field to one of the models

So, this was my Category model before:所以,这是我之前的类别 model:

class Category(models.Model):
    title = models.CharField(max_length=20)

    def __str__(self):
        return self.title

I had run makemigrations and migrate commands and the app was working just fine我已经运行了 makemigrations 和 migrate 命令,并且该应用程序运行良好

Then i had to add one more field to the model:然后我不得不在 model 中再添加一个字段:

class Category(models.Model):
    restricted = models.BooleanField(default=False)
    title = models.CharField(max_length=20)

    def __str__(self):
        return self.title

Now when i run makemigrations, it gives the following error:现在,当我运行 makemigrations 时,它给出了以下错误:

return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: events_category返回 Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: events_category

first it gave "no such column" error, but i don't really care about the data right now so i deleted the sqlite file and all migrations and started over, that's when this error showed up首先它给出了“没有这样的列”错误,但我现在并不关心数据所以我删除了 sqlite 文件和所有迁移并重新开始,就在这个错误出现的时候

The model has been set up as a foreign key in another model called Post: model 已在另一个名为 Post 的 model 中设置为外键:

class Post(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, default=DEFAULT_EXAM_ID)
    # and other fields...

Can someone please help me perform migrations properly after i added this field??添加此字段后,有人可以帮我正确执行迁移吗?

Delete the latest migrations and remigrate.删除最新的迁移并重新迁移。 The migration files are the files in the migrations folder in your specific application迁移文件是特定应用程序中迁移文件夹中的文件

still if the error exist, clear the migrations again.如果错误仍然存在,请再次清除迁移。 Now Remove the added Model.现在删除添加的 Model。 migrate without error.迁移没有错误。 Then add the model again and remigrate.然后再次添加 model 并重新迁移。

This error pops up when you try to load data before the tables are created.当您在创建表之前尝试加载数据时会弹出此错误。 You might have an import statement that attempts to load the data before migrate has been done.您可能有一个 import 语句尝试在migrate完成之前加载数据。

Try commenting out import statement that load models and do makemigrations and migrate尝试注释掉加载模型并进行makemigrationsmigrate的 import 语句

Resolution:解析度:

  1. Comment the newly added field and do fake migrations.评论新添加的字段并进行虚假迁移。
  • python manage.py makemigrations appname python manage.py makemigrations appname
  • python manaage.py migrate appname --fake python manaage.py migrate appname --fake
  1. Uncomment the same line and do normal migrate.取消注释同一行并进行正常迁移。
  • python manage.py makemigrations appname python manage.py makemigrations appname
  • python manaage.py migrate appname python manaage.py 迁移应用程序名称

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

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