pythonpypika

python match operator function based on condition


I'm a bit confused to uses multiple conditions while generating queries using pypika with the operator.

from pypika import Field, Query

query = Query.from_('test').select('column1','column2')
query = query.where(operator.eq(Field('column1'), 12))

With the above code I can add condition with operator.eq for equal and we can have other operations as follows.

operator.lt(a, b)
operator.le(a, b)
operator.eq(a, b)
operator.ne(a, b)
operator.ge(a, b)
operator.gt(a, b)
operator.not

In my case I get the operation value dynamically like

Equal
NotEqual
LessThan
LessThanOrEqual
GreaterThan
GreaterThanOrEqual

How can I form the query without adding lots of if conditions? instead, I am trying to find operator.eq, operator.le(a, b) with just Equal, LessThanOrEqual to a function and use them to where condition?

query = query.where(operator.eq(Field('column1'), 12))

Solution

  • Use a python dict, like this:

    import operator
    
    
    operations = {
        'Equal': operator.eq,
        'NotEqual': operator.ne,
        'LessThan': operator.lt,
        'LessThanOrEqual': operator.le,
        'GreaterThan': operator.gt,
        'GreaterThanOrEqual': operator.ge,
    }
    

    and use it like this

    query = query.where(operations[key](Field('column1'), 12))
    

    where key = 'LessThan' # Or NotEqual, Equal