18

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?

1
  • 1
    In case it is in order to fix migrations to a newer Django version, yes, but do not semantically change the migrations, since a database might already have executed migrations, and thus if you change it semantically, then it is possible the database gets out of sync. Aug 20, 2018 at 15:00

2 Answers 2

19

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.

9

To update your code to Django 2

(.*)models.ForeignKey\((((?!on_delete).)*)\)\)
$1models.ForeignKey($2, on_delete=models.CASCADE))

field=models.ForeignKey\((((?!on_delete).)*)\)
field=models.ForeignKey($1, on_delete=models.CASCADE)

(.*)models.OneToOneField\((((?!on_delete).)*)\)\)
$1models.OneToOneField($2, on_delete=models.CASCADE))

You can use these 3 regexes to update your codebase with search and replace feature. Of course, step over by checking each replacement, but having a regex will save you time.

1
  • 2
    Saved a lot of time. Thanks. @EralpB Jul 28, 2020 at 12:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.