views:

59

answers:

2

In my AppEngine project I have a need to use a certain filter as a base then apply various different extra filters to the end, retrieving the different result sets separately. e.g.:

base_query = MyModel.all().filter('mainfilter', 123)

Then I need to use the results of various sub queries separately:

subquery1 = basequery.filter('subfilter1', 'xyz')
#Do something with subquery1 results here

subquery2 = basequery.filter('subfilter2', 'abc')
#Do something with subquery2 results here

Unfortunately 'filter()' affects the state of the basequery Query instance, rather than just returning a modified version. Is there any way to duplicate the Query object and use it as a base? Is there perhaps a standard Python way of duping an object that could be used?

The extra filters are actually applied by the results of different forms dynamically within a wizard, and they use the 'running total' of the query in their branch to assess whether to ask further questions.

Obviously I could pass around a rudimentary stack of filter criteria, but I'd rather use the Query itself if possible, as it adds simplicity and elegance to the solution.

+2  A: 

There's no officially approved (Eg, not likely to break) way to do this. Simply creating the query afresh from the parameters when you need it is your best option.

Nick Johnson
I feared as much. Thanks for confirming.
Steve Mayne
+2  A: 

As Nick has said, you better create the query again, but you can still avoid repeating yourself. A good way to do that would be like this:

#inside a request handler

def create_base_query():
  return MyModel.all().filter('mainfilter', 123)

subquery1 = create_base_query().filter('subfilter1', 'xyz')
#Do something with subquery1 results here

subquery2 = create_base_query().filter('subfilter2', 'abc')
#Do something with subquery2 results here
jbochi
Thanks jbochi, I did something very similar to this in the end. I decided to pass function references where formerly I was passing Query objects. This allowed the necessary chaining of query-generation through the nodes in the wizard.
Steve Mayne