Django迁移:关系已经存在 [英] Django migrations : relation already exists

查看:245
本文介绍了Django迁移:关系已经存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django模型迁移方面遇到麻烦. 我的应用程序中有一些模型,并且内部已经有一些数据. 当我在应用程序中添加一些模型并运行makemigrations时,该应用程序报告没有更改. 我知道有时在迁移时会出现一些错误,因此我删除了数据库中的django_migrations表并再次运行makemigrations,现在程序找到了我的新字段.

I have trouble with django model migrations. I have some models in my app, and I already have some data inside. When I added some models in my application, and I run makemigrations, the app report that there is no change. I know that sometimes some errors came when migrate, so I delete django_migrations table in my database and run makemigrations again, and now program found my new fields.

现在的问题是,如果我运行migrate系统,请告诉我某些表已经存在. (没关系,没错,因为他们知道).我不想删除这些表,因为我已经有数据了.

The problem now is that if I run migrate system tell me that some tables already exist. (Which is ok and correct, because they do). I don't want to delete those tables, because I have data already inside.

我无法运行migrate --fake,因为程序会认为我已经拥有所有个表,这是不正确的.

I can't run migrate --fake, because program will think that I already have all the tables, which is not true.

因此,我正在寻找一种告诉程序的方法:如果表存在,请运行迁移. (--fake它)

So, I am looking for a way to tell the program : run migration, if table exist skip it. (--fake it)

另一个问题是为什么这会发生在我身上,makemigrations无法识别我的更改(某些缓存问题,...)?

Another question is why is this happening to me, that makemigrations don't recognise my changes (some cache problems,...)?

推荐答案

这种方法怎么样?

python manage.py makemigrations

python manage.py makemigrations

(如果您已经准备好迁移文件,请跳过此步骤)

(Skip this step if you have already have migration file ready)

它将为该软件包创建迁移,可以说一个像0001_initial.py这样的名称

It will create migrations for that package lets say with a name like 0001_initial.py

手动编辑文件,以便在那里删除所有已在数据库中创建的模型.

Edit the file manually so that you delete all models there except that was already created in database.

现在,您进行了假迁移.这将使您的数据库与模型同步.

Now you do a fake migration. This will sync your database with models.

python manage.py migration --fake

python manage.py migrate --fake

然后再次运行makemigrations以创建其余的表以及一个新的迁移文件.

Then run makemigrations again to have rest of the tables created along with a new migration file.

python manage.py makemigrations

python manage.py makemigrations

关于您的其他问题,为什么makemigrations无法重新划分您的模型可能是由于以下原因:

Regarding your other question, Why makemigrations didn't recogonize your models can be because of reasons like:

  1. 这些更改的迁移已存在于某些迁移文件中.
  2. 您错过了在INSTALLED_APPS中提及package_name的事情,但我相信您是在这里完成的.

这篇关于Django迁移:关系已经存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆