John D
John D

Reputation: 295

how to dynamically modify the attribute in a query using sqlalchemy

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?

Upvotes: 0

Views: 149

Answers (2)

c8999c 3f964f64
c8999c 3f964f64

Reputation: 1627

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

Upvotes: 0

edg
edg

Reputation: 1190

You can try to use getattr :

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

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

Upvotes: 2

Related Questions