使用GenericForeignKey对象数组进行Queryset过滤
这是个问题。
我有一个表格,里面记录了用户和一个通过通用外键(GenericForeignKey)定义的对象之间的关系。
我可以这样获取这些对象的列表:
association_objects = Association.objects.filter(user = request.user)
这样会返回一个对象数组,我可以通过以下方式访问相关的对象:
association_object.context
所以我可以很容易地制作一个只包含上下文对象的数组。
现在,我需要查询另一个表中与上述关联数组中的任何对象相关的所有记录。
在一个理想的世界里,我可以这样做:
Action.objects.filter(context__in = associations)
其中那个表中的上下文也是一个通用外键。
然而,通用外键不能仅通过它的实际键属性进行过滤。你必须同时通过内容类型和主键来过滤……
我该怎么做呢?我唯一想到的办法是把内容类型和ID分成两个单独的数组,然后对这两个属性进行__in过滤,但这似乎并不实际。
有没有人有好的主意?
相关问题:
2 个回答
-1
试试这个:
# I assume that association_objects is a QuerySet
association_ids = association_objects.value_list("id", flat=True)
content_type = ContentType.objects.get_for_model(Association)
actions = Action.objects.filter(content_type=content_type,
object_id__in=association_ids)
2
from django.contrib.contenttypes.models import ContentType
ct = ContentType.objects.get_for_model(Action)
action_ids = association_objects.values_list("object_id", flat=True)\
.filter(content_type=ct)
actions = Action.objects.filter(pk__in=action_ids)
(假设你的 GenericForeignKey
包含了 content_type
和 object_id
!)