About External Functions in Data Migrations

If your data migration must use an external function, ensure that the function accepts the model as an argument and uses it instead of importing the model directly from the app.

def forwards(apps, schema_editor):
    from .utilities import detect_languages

    # Get the historical model
    Article = apps.get_model("articles", "Article")

    # Pass the historical model to avoid issues
    detect_languages(Article)

When called from regular (runtime) code, the function will use the actual model. When called from a migration, it will use the historical model provided by apps.get_model(). This ensures historical integrity and prevents issues caused by model changes over time.

Tips and Tricks Programming Development Django 5.x Django 4.2 Django 3.2