Home > Software design >  how to dynamically modify the attribute in a query using sqlalchemy
how to dynamically modify the attribute in a query using sqlalchemy

Time:08-05

I am using sqlalchemy and i wonder if its possible to dynamically modify an attribute of a class while doing a query

if school == "abc":
         school_data = (
             meta.session.query(
                 model.School.name, <=== HERE
...

i want to be able to dynamically change .name. to another field, is it possible with python and sqlalchemy?

CodePudding user response:

You can try to use getattr :

if school == "abc":
   attr = "name"
else:
   attr = "id"

school_data = meta.session.query(getattr(model.School, attr) ...)

CodePudding user response:

I am not 100% sure if this is what you need, but you can do

c = "name"
getattr(table.c, c)

this gets a column from a table, named c - which can be any string. I am quite sure you can adapt this to model.School

  • Related