Chaining separate .where() clauses with OR instead of AND
See original GitHub issueI have an existing query in my code that I wish to further extend the query with additional WHERE criteria, but chained with OR instead of AND.
I can’t find a way to do this in peewee. Am I missing something? I am aware that I can dynamically chain multiple clauses with OR using reduce(operator.or_, clauses)
, but this is a different thing – it doesn’t help me to extend an additional query.
I believe I can achieve this with something like query._where = query._where | additional_criteria
, but this feels like a hack that requires knowledge of peewee’s implementation details, not the published API – always a bad idea.
I’m currently tinkering with a helper function something like the following:
def orwhere(query, *expressions):
import operator
query = query.clone()
reduced = reduce(operator.and_, expressions)
query._where = (query._where or True) | reduced # `or True` so that if it's the first expression in the clause, it still behaves consistently by broadening the queryset rather than restricting it.
return query
What do you think about adding .orwhere() to the query API? Or is there a better way that I’m missing?
Issue Analytics
- State:
- Created 9 years ago
- Comments:9 (6 by maintainers)
Top GitHub Comments
Sorry for necroposting but I have exactly the same issue. Actually this problem is not related with peewee. E.g. django ORM has the same API. If you want to extend your query you need to work with expression instead of query:
The best way is to:
You can use
operator.and_
to AND- them together.