从django Q查询弹出查询?

时间:2012-09-11 21:05:09

标签: python django django-q

我正在使用看起来像这样的查询:

    filters = Q(is_default = False)
    # Build the excludes and filters dynamically 
    if cut:
        filters = filters & Q(mailbagstats__num_letters2__gt = int(cut) )

鉴于filters Q查询,我可以pop其中一个查询吗?

我想从此Q查询中删除Q(mailbagstats__num_letters2__gt= int(cut) )查询,以获取新的过滤器。

通常情况下,我使用列表和reduce,但这个是通过Q() & Q()构建的,因此我不确定如何修改它。

感谢您提供任何意见!

2 个答案:

答案 0 :(得分:5)

你可以pop他们:

>>> filter = Q(a=True)
>>> filter = filter & Q(b=True)
>>> filter.children
[('a', True), ('b', True)]
>>> filter.children.pop()
('b', True)
>>> filter.children
[('a', True)]

答案 1 :(得分:1)

为什么不使用列表并在最后制作过滤器?

filters = []
filters.append(Q(is_default = False))
# Build the excludes and filters dynamically 
if cut:
    filters.append(Q(mailbagstats__num_letters2__gt = int(cut)))

# I want to pop the last one
filters.pop()

# build the filter before making the query
# Note that this call will remove an element from the filters list
filters_for_query = reduce(lambda a, x: a & x, filters, filters.pop())

Model.objects.filter(filters_for_query)