【问题标题】:Django: subsequent OR filterDjango:后续 OR 过滤器
【发布时间】:2014-02-14 17:09:14
【问题描述】:

我有一组带有 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

当我查看查询时,列表中每个对象的单独过滤器在逻辑上与过滤器进行了逻辑与运算。有没有办法可以逻辑或它?我试过这个:

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)
    )

但它实际上并没有排除任何记录,因为 or 允许它们进入。

【问题讨论】:

    标签: django filter django-queryset


    【解决方案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)
    

    【讨论】:

    • 太棒了,谢谢,我不知道如何构建过滤器,不知道我可以称之为 Q() 然后添加它。尝试使用字符串构造,然后尝试 eval(),但我知道这不是最合适的解决方案。完美运行!
    • 太棒了!很高兴它有帮助:)
    猜你喜欢
    • 2019-02-08
    • 2014-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2018-05-15
    相关资源
    最近更新 更多