Search code examples
pythondjangopython-3.xdjango-2.1

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?


Solution

  • 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.