【问题标题】:Migrating models of dependencies when changing DEFAULT_AUTO_FIELD更改 DEFAULT_AUTO_FIELD 时迁移依赖关系模型
【发布时间】:2021-07-04 11:18:17
【问题描述】:

我正在使用 Django 3.2。我已将此行更改为 settings.py:

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

然后我运行了这些命令:

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

makemigrations 命令为我的应用程序创建新的迁移文件,不仅是我创建的应用程序,还包括我的依赖项。比如我用的是django-allauth,这个文件是在我的虚拟环境(virtualenv)中创建的:

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

django-allauth 未附带此文件。当我从 git 部署这个应用程序时,这个文件不包括在内。

我应该怎么做?如何切换DEFAULT_AUTO_FIELD 而无需为django-allauth 等依赖项创建新的迁移文件?

【问题讨论】:

  • 在您的依赖项完成之前不要更新到 Django 3.2。个别应用程序可以设置AppConfig.default_auto_field 来指定默认自动字段以供其应用程序使用。我相信大多数流行的软件包都会将其添加到他们的应用程序配置中以防止此类情况发生。

标签: django django-migrations


【解决方案1】:

理想情况下,您的第三方依赖项将在apps.py 中找到的配置中包含这一行:

from django.apps import AppConfig

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

在等待上游依赖项更新其apps.py 或迁移文件时,您可以自己覆盖应用配置。如果它不存在,请在您的主应用程序目录中创建一个apps.py 文件(例如:project/apps.py),并覆盖依赖项的配置。在此示例中,我将覆盖 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'

然后将settings.py 中的INSTALLED_APPS 修改为如下所示,替换本示例中django-allauth 的旧条目:

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

如果依赖项没有要覆盖的apps.py 文件,您仍然可以像这样在project/apps.py 中创建AppConfig 子类:

from django.apps import AppConfig

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

现在当您运行python manage.py makemigrations 时,不应为依赖项创建迁移文件。

【讨论】:

  • 如果你用django-allauth试试这个,你可能会遇到this bug
猜你喜欢
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 2016-04-20
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
相关资源
最近更新 更多