GenericForeignKey
与 一起使用时,UUIDField
从通用对象的查询集中获取“真实模型”的查询集的推荐方法是什么?
以下是我正在测试的模型:
import uuid
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Foo(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4)
class Generic(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.CharField(max_length=255)
content_object = GenericForeignKey()
这就是我到目前为止所尝试的:
>>> from django.db.models import Subquery
>>> from foo.models import Foo, Generic
>>> f = Foo.objects.create()
>>> g = Generic.objects.create(content_object=f)
>>> Foo.objects.filter(id__in=Subquery(Generic.objects.all().values('object_id')))
<QuerySet []>
>>> Generic.objects.get().object_id
'997eaf64-a115-4f48-b3ac-8cbcc21274a8'
>>> Foo.objects.get().pk
UUID('997eaf64-a115-4f48-b3ac-8cbcc21274a8')
我猜这与保存的 UUID 没有UUIDField
. 因为我需要其他具有整数和字符串作为主键的模型,所以我object_id
无法做到。UUIDField
我正在使用 Django 1.11,但我也测试了 Django 2.0,它有同样的问题。