我需要使用動態列及其值來動態生成/構建sqlalchemy查詢。在sqlalchemy python中構建動態過濾器
示例 - 我在SQL中有一個名爲「Convo」的表,它有像UserID,ConvoID,ContactID這樣的列。
我需要根據以下標準獲取行。
criteria = (('UserID', 2), ('ConvoID', 1) ,('ContactID', 353))
我已經對此使用了「烘焙查詢」邏輯。但有些我如何不能成功運行此查詢。
以下是我的代碼。
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()
我得到錯誤的 -
AttributeError: type object 'Convo' has no attribute 'key1'
請幫我這個
你可能想'getattr(tablename,key1)'而不是'tablename.key1'。 – univerio