我试图在python中构建一个查询,我正在寻找一种在字符串中间附加WHERE条件的优雅方法:
def get_raw_queryset(frequency=None, where_condition=None):
qs = "SELECT id, COUNT(*) AS count FROM user_transaction_log " \
# I WANT TO APPEND A WHERE ONLY IF not None
if where_condition:
"WHERE .... = 1" \
"GROUP BY type , strftime('{0}', datetime) ORDER BY id" \
.format(frequency)
return qs
答案 0 :(得分:4)
只要您可以安全地评估WHERE字符串,即使where_condition
不是字符串,这也会有效:
"SELECT ..." + bool(where_condition) * ("WHERE ...") + "GROUP ..."
我希望您能够非常小心地避免SQL注入。