Search code examples
peewee

Peewee how to set query's operators and logics by variable?


I want to build query dynamically with peewee.

Example query:

User.select()
    .where(
        (User.full_name=="test") | 
        (User.email=="test")
    )

Is there any possible like that?

op1 = "=="
op2 = "!="
logic = "|"
User.select()
    .where(
        (User.full_name op1 "test") logic
        (User.email op2 "test")
    )

Solution

  • You can use the operator module.

    import operator
    name_is_test = operator.eq(User.full_name, 'test')
    email_is_test = operator.eq(User.email, 'test')
    User.select().where(operator.or_(name_is_test, email_is_test)