Search code examples
pythonpeewee

Peewee: simple where condition that is always True


I would like to do something like this:

conditions = Model.attribute == Model.attribute
conditions &= (more conditions here)

Model.select().where(conditions)

Is there something similar to Django's Q object to replace the first line?


Solution

  • You can get such condition using the following expression:

    from peewee import Value
    ...
    
    def TRUE_condition():
       return (Value(1) == Value(1))
    
    ...
    conditions = TRUE_condition()
    conditions &= (Model.attribute == 42)
    Model.select().where(conditions)
    

    However this might look like a hack. A more elegant solution is to collect all conditions in a list and then reduce them with the and operator:

    from functools import reduce
    from peewee import operator
    
    conditions = list()
    conditions.append(Model.attribute == 42)
    conditions.append(Model.active == True)
    condition = reduce(operator.and_, conditions)
    Model.select().where(condition)