0

我有一个包含以下内容的表格:

content_type = models.ForeignKey(ContentType, null=True, default=None)
object_id = models.PositiveIntegerField(null=True, default=None)
content_object = generic.GenericForeignKey('content_type', 'object_id')

我希望能够在content_typeisNull或如果content_type不是的情况下进行过滤Null,我希望它检查active特定对象中的字段并确保它是“Y”。我该如何进行比较?

我检查了许多网站,包括以下内容:

http://ui.co.id/blog/generic-field-filtering-in-django

编辑

我对此的唯一解决方案是for loop在过滤器语句之后循环遍历并消除任何没有正确active字段的对象。这效率低下……有更好的方法吗?

4

1 回答 1

0

在这种情况下,您可能会执行以下操作:

情况1:

result = []
result += Model.objects.filter(content_type__isnull=True)

案例2:

active_object_ids = ObjectClass.objects.filter(active='Y').values_list('id', flat=True)
result += Model.objects.filter(object_id__in = active_object_ids)

唯一的缺点是在情况 2 中,您可能必须收集 GFK 链接的所有对象的所有 ID。此外,因为每当您保存 content_object 时,content_type 都会与它一起保存,因此您无需在第二种情况下测试 content_type。

于 2012-10-19T22:20:14.743 回答