我有一组带有GeneraricForeignKey字段的项目,我想循环遍历一组对象以获取附加到这些对象的项目,就像这样。我想在所有记录上执行单个查询集,然后添加过滤器以获取附加到列表中对象的项目。
像这样:
models.py:
from django.contrib.contenttypes.models import ContentType
class Item(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(db_index=True)
content_object = generic.GenericForeignKey('content_type', 'object_id')
views.py:
my_objects = list()
my_objects.append(SomeObject.objects.get(id=1))
my_objects.append(SomeObject.objects.get(id=2))
items = Item.objects.all()
for obj in my_objects:
items = items.filter(content_type=ContentType.objects.get_for_model(obj), object_id=obj.id)
return items
当我查看此查询时,列表中每个对象的单独过滤器将与过滤器进行逻辑AND运算。有没有办法可以合乎逻辑或者它?我试过这个:
from django.db.models import Q
items = Item.objects.all()
for obj in my_objects:
items = items.filter(
Q(id__in=items)
| Q(content_type=ContentType.objects.get_for_model(obj), object_id=obj.id)
)
但它实际上并不排除任何记录,因为它们允许它们进入。
答案 0 :(得分:1)
您需要做的是分别构建ORed子句:
object_filter = Q()
for obj in my_objects:
object_filter = object_filter | Q(content_type=ContentType.objects.get_for_model(obj),
object_id=obj.id)
items = Item.objects.filter(object_filter)