5

我一直在使用 UUIDField 作为我在 Django 中的主键。我的项目具有继承字段的模型层次结构,在顶部,我有以下超类:

import uuid
from django.db import models

class HasIDMixin(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True, name='id')

更新到 Django 3.2.4 后,我收到以下警告:

WARNINGS:
app_base.MyProject: (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 AppBaseConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.

按照警告的建议,我尝试了 settings.py 中的 DEFAULT_AUTO_FIELD 和 app_config 中的 default_auto_field ,但出现以下错误:

ValueError: Primary key 'django.db.models.UUIDField' referred by DEFAULT_AUTO_FIELD must subclass AutoField.

我已经看到其他人使用 UUIDField 和 AutoField ( https://code.djangoproject.com/ticket/32577 ) 的自定义子类来解决这个问题,但没有发布任何可行的解决方案。这在 Django 3.2 中目前是否可行。^?如果不是,我应该找到不同的主键解决方案还是回滚?

4

1 回答 1

4

当没有将模型字段设置为该模型的主键时,Django 将自动向您的模型添加一个字段,该字段id将用作主键。这个自动添加的密钥通常是AutoField. 从 Django 3.2 开始,Django 允许您通过设置来设置AutoField这些自动生成的主键字段的类型DEFAULT_AUTO_FIELD

考虑到您为模型显式设置主键,Django 不会为其生成字段。但是您仍然应该指定DEFAULT_AUTO_FIELD,因为您可能有一些没有指定主键的模型。您可以安全地保持UUIDField模型原样,也可以DEFAULT_AUTO_FIELD这样设置:

DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' # Or one of the other options as per your choice
于 2021-06-06T17:10:26.380 回答