Search code examples
pythonsqlpeewee

dynamic field query in peewee


I have modal defined and able to get result with select query:

country = 'usa'
User.select(User.email, User.username).where(User.country==country)

I want to filter this dynamic field name, like:

field = 'country'
country = 'usa'
User.select(User.email, User.username).where(User[field]==country)

Is it possible to do that?


Solution

  • Try attrgetter:

    from operator import attrgetter
    
    
    field = 'country'
    country = 'usa'
    User.select(User.email, User.username).where(attrgetter(field)(User)==country)