Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it correct to modify old migration files in Django?

I'm trying to migrate my Django project from Python 2.7/Django 1.11 to Python 3.7/Django 2.1.

And I'm a little bit confused with one issue.

Django 2.1 marks as errors all models.ForeignKey(...) code strings in my project with:

TypeError: __init__() missing 1 required positional argument: 'on_delete'

It is because since Django 2.x, 'on_delete' method is required for ForeignKey fields (Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries)

If you'll read this post, solution is pretty simple, you just need to add one of 'on_delete' options, for example: models.ForeignKey(..., on_delete=models.CASCADE,)

But Django complains not only about actual 'models.py' file but also about all (!) migrations that include "ForeignKey" fields adding or alteration.

So my question is, is it safe to modify old migration files in Django? And is it what I should do in this situation?

like image 366
kostr22 Avatar asked Aug 20 '18 14:08

kostr22


People also ask

How do I fix migration issues in Django?

you can either: temporarily remove your migration, execute python manage.py migrate, add again your migration and re-execute python manage.py migrate. Use this case if the migrations refer to different models and you want different migration files for each one of them.

Is it okay to delete migrations in Django?

Yes you can delete the migrations in django but it can create following errors. If you change the model again and create migration, it will have all the information from the beginning of model creation so when you migrate the migration in db you will get the error that “this table or column already present in table”.

Can I rename Django migration file?

So the steps to renaming a migration are: Rename the file. Repoint any dependencies to the new file. If the renamed migration was already applied, apply it again using --fake .


1 Answers

Yes, that's the intended upgrade path as described in the 1.9 release notes:

In order to increase awareness about cascading model deletion, the on_delete argument of ForeignKey and OneToOneField will be required in Django 2.0.

Update models and existing migrations to explicitly set the argument. Since the default is models.CASCADE, add on_delete=models.CASCADE to all ForeignKey and OneToOneFields that don’t use a different option. You can also pass it as the second positional argument if you don’t care about compatibility with older versions of Django.

like image 140
knbk Avatar answered Sep 17 '22 19:09

knbk