[Fixed]-Django: ContentTypes during migration while running tests

8πŸ‘

βœ…

This is what ended up working for me. First, import update_contenttypes:

from django.contrib.contenttypes.management import update_contenttypes

Second, list the initial ContentType migration as a dependency:

dependencies = [
    ('contenttypes', '0001_initial'),
    ...
]

Finally, in the forward migration function (invoked via RunPython in the migration operations):

# Ensure ContentType objects exist at this point:
app_config = apps.get_app_config('my_app')
app_config.models_module = app_config.models_module or True

update_contenttypes(app_config)

You may need to run the above code for more than one app_config. You can obtain the all the app_config objects using apps.get_app_configs() and iterate.

πŸ‘€salezica

Leave a comment