how to access data attributes of a class object


N

namrata

Hi,

i am new to python and sqlalchemy. so my doubt mite be very silly.

I am creating an instance of a class. for example let the class be
Temp and the attributes of the class be first_name and last_name.
in order to access the attributes i will usually use the following
command:
a = Temp()
a.last_name = "*******"

now, i am using sqlalchemy and mapping a table in postgresql to
python. i am trying to implement a method where i can pass the column
name and a value to the method. the method will fire a query for that
column name and value. the query is as follows:
query = session.query(Temp).query.filter(Temp.last_name == some_value)

the column name passed to the method is stored in a local variable say
'col_name'
how do i pass this local variable to the query. when i try the below
query it throws an error saying col_name is not an attirbute
query = session.query(Temp).query.filter(Temp.col_name == some_value)

please help.
thanks in advance.
 
Ad

Advertisements

P

Peter Otten

namrata said:
I am creating an instance of a class. for example let the class be
Temp and the attributes of the class be first_name and last_name.
in order to access the attributes i will usually use the following
command:
a = Temp()
a.last_name = "*******"

now, i am using sqlalchemy and mapping a table in postgresql to
python. i am trying to implement a method where i can pass the column
name and a value to the method. the method will fire a query for that
column name and value. the query is as follows:
query = session.query(Temp).query.filter(Temp.last_name == some_value)

the column name passed to the method is stored in a local variable say
'col_name'
how do i pass this local variable to the query. when i try the below
query it throws an error saying col_name is not an attirbute
query = session.query(Temp).query.filter(Temp.col_name == some_value)

I'd guess you can use getattr():

query = session.query(Temp).query.filter(getattr(Temp, col_name) ==
some_value)

Peter
 
Ad

Advertisements


Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top