keeping in mind it's absolutely not safe to do this with *untrusted* user input, you'd use exec/eval:

globals_ = globals()
locals_ = {}
exec("%s = map_model" % model, globals_, locals_)
q = session.query(model).filter(eval(condition, globals_, locals_))




On 03/22/2017 10:00 AM, Vijaya Sekar wrote:
Hi everyone,

I have an string which has the condition to be performed while
retrieving from database. I automap my model and make reference to it by
using another variable name.
How can achieve retrieve data by filter which is in string?

here is my code

from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import MetaData


engine = create_engine("sqlite:///chinook.db", echo = False)

metadata = MetaData()
model = 'employees'
condition = 'employees.City == "Chennai"'
metadata.reflect(engine, only=[model])
base = automap_base(metadata=metadata)
base.prepare()
map_model = base.classes[model]
session = Session(engine)
retrieve = session.query(map_model).filter(condition)
for i in retrieve:
print(i.EmployeeId)



--
SQLAlchemy -
The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and
Verifiable Example. See http://stackoverflow.com/help/mcve for a full
description.
---
You received this message because you are subscribed to the Google
Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send
an email to sqlalchemy+unsubscr...@googlegroups.com
<mailto:sqlalchemy+unsubscr...@googlegroups.com>.
To post to this group, send email to sqlalchemy@googlegroups.com
<mailto:sqlalchemy@googlegroups.com>.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

--
SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper

http://www.sqlalchemy.org/

To post example code, please provide an MCVE: Minimal, Complete, and Verifiable 
Example.  See  http://stackoverflow.com/help/mcve for a full description.
--- You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to