Search code examples
pythondjangodjango-q

Popping a query from django Q query?


I'm working with a query that looks like so:

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

Given the filters Q query, can I pop one of the queries?

I'd like to remove the Q(mailbagstats__num_letters2__gt= int(cut) ) query from this Q query for a new filter down the line.

Normally, I use lists and reduce but this one is constructed via Q() & Q() so I'm not sure how to modify it.

Thanks for any input you might have!


Solution

  • You can pop them:

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