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.

So in practice, do this


# 0006_populate_has_chickens.py
from django.db import migrations

def forwards(apps, schema_editor):
    ChickenCoopLocations = apps.get_model("territory", "ChickenCoopLocations")
    for item in in ChickenCoopLocations.objects.all():
        item.has_chickens = does_have_chickens(item.pk)
        item.save()

class Migration(migrations.Migration):
    dependencies = [("cases", "0005_auto_foo.py")]
    operations = [migrations.RunPython(forwards)]

def does_have_chickens(pk):
    ...

Instead of this


# 0006_populate_has_chickens.py
from django.db import migrations
from territory import models

def forwards(apps, schema_editor):
    for item in in models.ChickenCoopLocations.objects.all():
        item.has_chickens = does_have_chickens(item.pk)
        item.save()

class Migration(migrations.Migration):
    dependencies = [("cases", "0005_auto_does_have_chickens.py")]
    operations = [migrations.RunPython(forwards)]


def does_have_chickens(pk):
    ...


Are you affected by this? Audit your codebase in seconds to find out.

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.