Importing models.py into migrations

It's better to use apps.get_model, which guarantees the Model's fields will reflect the fields in the database even if models.py is vastly out of step with the database.

The fields in Django's models.py must agree with the schema in the database. When Django performs database read or write operations it uses the fields in your models.py to determine the name of the database fields to SELECT and INSERT.

If models.py includes fields that are not yet in the database schema then the database will throw an error.

If our GitHub code review bot spots this issue in your pull request it gives this advice:

django-doctorbotsuggested changes just now
tasks.py
1
+
from models import MyModel
Suggested changes
-
from models import MyModel
-
 
-
    MyModel.objects.get(...)
+
    apps.get_model("core", "MyModel").objects.get(...)
Commit suggestion

It's better to use apps.get_model, which guarantees the Model's fields will reflect the fields in the database even if models.py is vastly out of step with the database.

Read more
2
+
3
+
def forwards(apps, schema_editor):
4
+
    MyModel.objects.get(...)
Update tasks.py
We're your Django code review copilot. Get code improvements right in your pull request with our GitHub code review bot.

Configuring this check

Code Review Doctor will run this check by default. No configuration is needed but the check can be turned on/off using check code migration-model-import in your pyproject.toml file.

Read more about configuring Code Review Doctor.