I want to query the datastore on a range (0-4) of possible criteria, based on a user request. Queries in NDB are built as follows:
query = Account.query(Account.userid >= 40, Account.userid < 50)
Is there any way I could do something like:
myfilter = []
myfilter.push('Account.userid >= 40')
myfilter.push('Account.userid < 50')
myfilter.push('Account.name == "John"')
query = Account.query(*myfilter)
There may be anywhere from 0 to 4 filter arguments, depending on conditionals. My assumption (which could be wrong) is that it is more optimal to omit a filter than have a catch-all (ex. Account.userid == *) if there is no need for it.
I know you can chain filters but since query objects are immutable, not sure this helps me.
Yes, it is possible. From Filtering by Property Values:
You can use such incremental query build technique to conditionally add filters as needed. For example (this assumes an overall AND between the optional conditions):
The above snippet specifically takes advantage of the imutability of the query object, each assignment to the
query
variable actually storing the new query object obtained by applying the respective filter. Confirmed by the associated log messages.