【问题标题】:Popping a query from django Q query?从 django Q 查询中弹出查询?
【发布时间】:2012-09-04 20:48:33
【问题描述】:

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

    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() 构造的,所以我不知道如何修改它。

感谢您的任何意见!

【问题讨论】:

    标签: python django django-q


    【解决方案1】:

    你可以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)]
    

    【讨论】:

    • 非常好!谢谢!我将编写一个函数,它接受一个键并遍历列表(children 也需要递归)并弹出它们!
    【解决方案2】:

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

    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)
    

    【讨论】:

    • children 属性是一个列表
    • 是的,你是对的。我只是提出其他解决方案。我喜欢处理列表。对于这个特定问题,您的答案更好。 +1 ;)
    • 不,没关系。我并不是说我的答案更好。只是指出不需要新列表,因为您已经有了一个:)
    • 嘿!我希望我们今晚能击败阿根廷! xD
    • 哈哈,@César,这对我们来说很难。你有一个非常强大的团队。而且,是的,你的答案更好。它直奔主题。
    猜你喜欢
    • 2015-02-28
    • 2014-08-12
    • 1970-01-01
    • 2012-10-16
    • 2015-11-12
    • 2014-02-06
    • 2015-07-15
    • 2015-06-23
    • 2014-03-25
    相关资源
    最近更新 更多