Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
803 views
in Technique[技术] by (71.8m points)

build dynamic filters in sqlalchemy python

I need to generate/build sqlalchemy query dynamically using dynamic columns and their values.

Example - I have a table in SQL called "Convo" and it has columns like - UserID, ConvoID, ContactID.

I need to get rows based on the below criteria.

criteria = (('UserID', 2), ('ConvoID', 1) ,('ContactID', 353))

I have used "Baked query" logic for this. But Some how I am not able to run this query successfully.

Below is the my code.

criteria = (('UserID', 2), ('ConvoID', 1) ,('ContactID', 353))
baked_query = bakery(lambda session: session.query(tablename))
for key1 in condition:
    baked_query += lambda q: q.filter(tablename.key1 == condition[key1])
    result = baked_query(self.session).all()

I am getting error as -

AttributeError: type object 'Convo' has no attribute 'key1'

Please help me out with this

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
criteria = (('UserID', 2), ('ConvoID', 1) ,('ContactID', 353))

query = session.query(tablename)
for _filter, value in criteria:
    query = query.filter(getattr(tablename, _filter) == value)
result = query.all()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...