Django:将“DEFAULT_AUTO_FIELD”添加到settings.py后,“AttributeError:类型对象'AutoField'没有属性'rsplit'”

Chr*_*ash 2 django django-models django-settings

我刚刚将 Django 项目从 3.1.6 更新到 3.2.3。运行后python manage.py runserver,服务器运行时出现以下警告:

core.CoreUser: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
        HINT: Configure the DEFAULT_AUTO_FIELD setting or the CoreConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
Run Code Online (Sandbox Code Playgroud)

然后我记得在将项目从版本 < 3.2 更新到版本 >= 3.2 后需要添加一个DEFAULT_AUTO_FIELD设置,所以我这样做了:settings.py

core.CoreUser: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
        HINT: Configure the DEFAULT_AUTO_FIELD setting or the CoreConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
Run Code Online (Sandbox Code Playgroud)

然后我又尝试了python manage.py runserver一次,但这一次我收到了不同的警告:

(venv) C:\Users\Chris\my_project>python manage.py runserver
Traceback (most recent call last):
  ... (truncated for brevity)
  File "C:\Users\Chris\my_project\venv\lib\site-packages\django\utils\module_loading.py", line 13, in import_string
    module_path, class_name = dotted_path.rsplit('.', 1)
AttributeError: type object 'AutoField' has no attribute 'rsplit'
Run Code Online (Sandbox Code Playgroud)

我认为我的迁移或数据库的某些问题导致了问题,因此我删除了db.sqlite3应用程序的所有迁移。然后我运行了一个新的python manage.py makemigrations,但导致了同样的错误:AttributeError: type object 'AutoField' has no attribute 'rsplit'

任何想法为什么会发生这种情况?

Chr*_*ash 5

这是因为您需要用django.db.models.AutoField引号括起来以使其成为字符串,如下所示:

# settings.py

DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
Run Code Online (Sandbox Code Playgroud)

解决这种问题可能有点棘手,因为如果您使用真正的导入而不是点分模块路径作为字符串,Django 不会给您任何提示。请特别注意您在 中使用字符串settings.py