Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 592
Yuji 'Tomita' Tomita Avatar asked Sep 11 '12 21:09

Yuji 'Tomita' Tomita


People also ask

How do I run a query in Django?

Django gives you two ways of performing raw SQL queries: you can use Manager. raw() to perform raw queries and return model instances, or you can avoid the model layer entirely and execute custom SQL directly. Explore the ORM before using raw SQL!

What is Django Q?

Django Q is a native Django task queue, scheduler and worker application using Python multiprocessing.

What is PK in Django?

pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".


2 Answers

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)]
like image 179
César Avatar answered Oct 09 '22 12:10

César


Why don't you work with lists and made the filter at the end?

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)
like image 37
santiagobasulto Avatar answered Oct 09 '22 11:10

santiagobasulto