Search code examples
djangodjango-migrations

Migrating models of dependencies when changing DEFAULT_AUTO_FIELD


I'm using Django 3.2. I've changed added this line to settings.py:

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

I then ran these commands:

$ python manage.py makemigrations
$ python manage.py migrate

The makemigrations command creates new migration files for my apps, not just the apps that I have created, but also in my dependencies. For example, I'm using django-allauth, and this file was created in my virtual environment (virtualenv):

 .venv/lib/python3.8/site-packages/allauth/account/migrations/0003_auto_20210408_1526.py

This file is not shipped with django-allauth. When I deploy this application from git, this file is not included.

What should I do instead? How can I switch DEFAULT_AUTO_FIELD without the need to create new migration files for dependencies like django-allauth?


Solution

  • Ideally, your third party dependencies would include this line in the config found in apps.py:

    from django.apps import AppConfig
    
    class ExampleConfig(AppConfig):
        default_auto_field = 'django.db.models.AutoField'
    

    While waiting for upstream dependencies to update their apps.py or migration files, you can override the app config yourself. If it doesn't exist already, create an apps.py file in your main app directory (eg: project/apps.py), and override the config of a dependency. In this example, I'm overriding the config of django-allauth:

    from allauth.account.apps import AccountConfig
    from allauth.socialaccount.apps import SocialAccountConfig
    
    class ModifiedAccountConfig(AccountConfig):
        default_auto_field = 'django.db.models.AutoField'
    
    class ModifiedSocialAccountConfig(SocialAccountConfig):
        default_auto_field = 'django.db.models.AutoField'
    

    Then modify INSTALLED_APPS in settings.py to look like this, replacing the old entries for django-allauth in this example:

    INSTALLED_APPS = [
        # ....
        # replace: "allauth.account", with
        "projectname.apps.ModifiedAccountConfig",
        # replace: "allauth.socialaccount", with
        "projectname.apps.ModifiedSocialAccountConfig",
    ]
    

    If the dependency doesn't have an apps.py file to override, you can still create an AppConfig sub-class in project/apps.py like this:

    from django.apps import AppConfig
    
    class ModifiedExampleDependencyConfig(AppConfig):
        name = 'exampledependency' # the python module
        default_auto_field = 'django.db.models.AutoField'
    

    Now when you run python manage.py makemigrations, no migration files should be created for the dependencies.