Django: "AttributeError: type object 'AutoField' has no attribute 'rsplit'" after adding "DEFAULT_AUTO_FIELD" to settings.py
Django: "AttributeError: type object 'AutoField' has no attribute 'rsplit'" after adding "DEFAULT_AUTO_FIELD" to settings.py
我刚刚将我的 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'.
然后我记得我需要在将项目从<3.2版更新到>=3.2版的Django后添加一个DEFAULT_AUTO_FIELD
设置到settings.py
,所以我做了:
# settings.py
DEFAULT_AUTO_FIELD = django.db.models.AutoField
然后我再次尝试 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'
我认为问题是我的迁移或数据库引起的,所以我删除了 db.sqlite3
和应用程序的所有迁移。然后我运行一个新的python manage.py makemigrations
,只是导致了同样的错误:AttributeError: type object 'AutoField' has no attribute 'rsplit'
知道为什么会发生这种情况吗?
因为需要把django.db.models.AutoField
用引号括起来,变成字符串,像这样:
# settings.py
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
这种问题可能有点棘手,因为如果您使用真正的导入而不是点分模块路径作为字符串,Django 不会给您任何提示。请格外注意您在 settings.py
.
中使用字符串
我刚刚将我的 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'.
然后我记得我需要在将项目从<3.2版更新到>=3.2版的Django后添加一个DEFAULT_AUTO_FIELD
设置到settings.py
,所以我做了:
# settings.py
DEFAULT_AUTO_FIELD = django.db.models.AutoField
然后我再次尝试 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'
我认为问题是我的迁移或数据库引起的,所以我删除了 db.sqlite3
和应用程序的所有迁移。然后我运行一个新的python manage.py makemigrations
,只是导致了同样的错误:AttributeError: type object 'AutoField' has no attribute 'rsplit'
知道为什么会发生这种情况吗?
因为需要把django.db.models.AutoField
用引号括起来,变成字符串,像这样:
# settings.py
DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'
这种问题可能有点棘手,因为如果您使用真正的导入而不是点分模块路径作为字符串,Django 不会给您任何提示。请格外注意您在 settings.py
.