Home > Mobile >  Dynamically set columns to filter with ORM in SQLAlchemy
Dynamically set columns to filter with ORM in SQLAlchemy

Time:10-13

I cannot figure out how to set columns dynamically for filtering using the latest SQLalchemy style for ORM.

Basically, I want to create a wrapper function to be able to pass in any columns into the 'where' part of the statement, the idea would be:

def get_id(column, value):
    id = session.execute(select(Account.id).where(
       Account.column == value)).all()

    return id

My problem is that I cannot dynamically select the attribute of the Account object with Account[column] as I get the error: TypeError: 'DeclarativeMeta' object is not subscriptable

I know this is possible with Core by setting up table MetaData and using either account.c[column] or the column() function but I would be interested in an ORM solution as my tables are automapped.

Thanks for the help.

CodePudding user response:

Basically, you can use reflection features of Python, like this.

column_name = 'name';
getattr(Account, column_name) # This is equivalent to Account.name

But you can also use a ready-made API like this.

ids = [id for id, in session.query(Account.id).filter_by(**{column_name: value}).all()]

See Query API.

  • Related