UUIDField 没有属性 uuid4

UUIDField has no attribute uuid4

这是我的模型

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
import uuid

class PiO(models.Model): 
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # surrogate
    person = models.ForeignKey(Person, on_delete=models.PROTECT, max_length=25, blank=True)
    content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) # for the various organization types
    object_id = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) # the uuid of the specific org
    content_object = GenericForeignKey('content_type', 'object_id')

这是我的回溯

AttributeError: 'UUIDField' object has no attribute 'uuid4'.

请注意,这是专门引用 object_id 字段, 而不是 uuid (pk) 字段。作为测试,我注释掉了 object_id 字段。我确实 not 收到一个错误,因为没有 object_id 字段,检查继续到 12 行以外的新错误。

我用谷歌搜索了确切的短语并得到了

No results found for "AttributeError: 'UUIDField' object has no attribute 'uuid4'".

我所做的看起来与 the docs 一致。

我错过了什么?通用外键和/或内容类型的存在与它有什么关系吗?

问题是您的模型字段 uuid 与模块 uuid 冲突。

一种选择是重命名您的模型字段,例如:

class PiO(models.Model): 
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
    ...

另一种选择是将导入更改为 from uuid import uuid4,并更新默认值以使用 uuid4 而不是 uuid.uuid4

from uuid import uuid4

class PiO(models.Model): 
    uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False) # surrogate
    ...
    object_id = models.UUIDField(primary_key=False, default=uuid4, editable=False) # the uuid of the specific org