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?
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.
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”.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With