是否可以将内容类型与对象的非主键一起使用?

Is it possible to use contenttype with non primary key for the object?

我想在内容类型对象中使用非主键,如下所示:

我的内容类型模型:

class Vote(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id    = models.PositiveIntegerField()
    object       = generic.GenericForeignKey('content_type', 'object_uid')
    vote         = models.SmallIntegerField()

我的另一个模型是:

class Task(models.Model):
    uid=uid = models.UUIDField(default=uuid.uuid4, unique=True)
    title = models.CharField(_('Title'), max_length=128, help_text=_('Title'))
    votes = GenericRelation(Vote)

现在,模式已创建,我可以创建对象,但无法检索: 以下不起作用:

t = Task.objects.create(title='task1')
t.votes.all()

我收到以下错误:

django.db.utils.ProgrammingError: operator does not exist: uuid = integer
LINE 1: ..."content_type_id" = 19 AND "vote"."object_uid" = 16) ORDE...

现在我明白了这个错误,我明白它试图根据 uuid 评估整数。 有没有办法指示 django 它应该使用 uid 字段而不是 pk

简短回答:不,不可能让 GenericForeignKey 使用主键以外的任何其他目标字段。主键硬编码在 GenericForeignKeyGenericRelation 和一些支持 类(内联、相关描述符等)中。

如果你真的想使用 UUID 作为目标字段,那么你必须将 UUID 字段设置为目标模型的主键,并使用与 UUID 兼容的类型作为 Vote.object_id (例如 CharField,甚至 TextField – 这样您仍然可以指向具有整数主键的模型。