5

我正在处理一个看起来像这样的查询:

    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(mailbagstats__num_letters2__gt= int(cut) )从此 Q 查询中删除该查询,以获取新的过滤器。

通常,我使用列表,reduce但这个列表是通过构造的, Q() & Q()所以我不确定如何修改它。

感谢您提供的任何意见!

4

2 回答 2

6

你可以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)]
于 2012-09-11T21:13:48.570 回答
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)
于 2012-09-11T21:13:10.507 回答