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 we spot this issue in your GitHub pull request we give this advice:

tasks.pymaintainabilityhigh
-
from models import MyModel
-
 
def forwards(apps, schema_editor):
-
    MyModel.objects.get(...)
+
    apps.get_model("core", "MyModel").objects.get(...)

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
Protect your pull requests from over 40 types of common Django technical debts with our GitHub code review bot.

Configuring this check

Django 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 Django Doctor.