Querying from a django request Q?

I am working with a query that looks like this:

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 execute one of the queries?

I want to remove the Q(mailbagstats__num_letters2__gt= int(cut) ) query Q(mailbagstats__num_letters2__gt= int(cut) ) from this Q query for a new filter by line.

I usually use lists and reduce , but this method is created via Q() & Q() , so I'm not sure how to change it.

Thanks for any input you have.

+4
source share
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)] 
+5
source

Why don’t you work with lists and do not 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) 
+1
source

Source: https://habr.com/ru/post/1433659/


All Articles