6

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,它有同样的问题。

4

2 回答 2

4

主要的麻烦在于explicit type casts

所以,@Alasdair 的想法,你可以试试:

foo_content_type = ContentType.objects.get_for_model(Foo)
gids = Generic.objects.filter(content_type=foo_content_type)
# create list of uuid strings
gids = list(gids.values_list('object_id', flat=True))
Foo.objects.filter(pk__in=gids)

其他解决方案:您可以uuid向模型添加字段Generic。例如:

class Generic(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.CharField(max_length=255)
    content_object = GenericForeignKey()
    uuid4 = models.UUIDField(blank=True, null=True)

    def save(self, *args, **kwargs):
        try:
            self.uuid4 = uuid.UUID(self.object_id)
        except Exception as e:
            pass
        super().save(*args, **kwargs)

和查询集将看起来:

foo_content_type = ContentType.objects.get_for_model(Foo)
gids = Generic.objects.filter(content_type=foo_content_type).values('uuid4')
Foo.objects.filter(pk__in=gids)
于 2018-05-25T12:20:12.583 回答
0

尝试删除Subquery(). 您还需要按内容类型进行过滤。

foo_content_type = ContentType.objects.get_for_model(Foo)
Foo.objects.filter(
    id__in=Generic.objects.filter(content_type=foo_content_type).values('object_id'), 
)
于 2018-05-25T10:25:59.380 回答