Django: "AttributeError: type object ' AutoField'没有属性 'rsplit'“将 "DEFAULT_AUTO_FIELD"添加到settings.py后

标签 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'.

然后我想起在将项目从版本 < 3.2 更新到版本 >= 3.2 后,我需要向 settings.py 添加 DEFAULT_AUTO_FIELD 设置,所以我做了:

# 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: "AttributeError: type object ' AutoField'没有属性 'rsplit'“将 "DEFAULT_AUTO_FIELD"添加到settings.py后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67726034/

相关文章:

Django - "Include"几个模板中的一个 block ?模板标签?还有什么?

django - Django Admin 记录的排序顺序

python - Django 模型字段实际上是对相关模型中字段的引用

python - 每个应用程序的 django 设置 - 最佳实践?

python - django 从 root : FileNotFoundError 读取文件

Django admin GenericForeignKey 内联

django - 在ImageField upload_to路径中获取用户名

python - 在/admin/安装 jinja2 TemplateDoesNotExist 后

django - 如何从 django 交互式 shell 打印 TEMPLATE_DIRS 的值?

mysql - 如何获取服务器上未找到/未保存的所有 ImageField 的列表?