Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django migrations : relation already exists

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.

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.

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

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

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

like image 488
Marko Zadravec Avatar asked Jan 24 '26 19:01

Marko Zadravec


2 Answers

How about doing this way ?

python manage.py makemigrations

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

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 migrate --fake

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

python manage.py makemigrations

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

  1. Migrations for those changes are already there in some migration file.
  2. You missed it to mention package_name in INSTALLED_APPS but i believe you did it here.
like image 111
Ali Askar Avatar answered Jan 26 '26 11:01

Ali Askar


every time you make changes to your models, try these steps :

python manage.py makemigrations [your app name]

then:

python manage.py migrate

it should work fine. but remember if you have already data(rows) in your tables you should specify the default value for each one the queries.
if not, Django prompt you to specify the default value for them or you can just try to use blank=True or null=True in your fields like below :

website         = models.URLField(blank=True)
like image 36
Farzan Ahmadi Avatar answered Jan 26 '26 09:01

Farzan Ahmadi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!