在python中的查询中间追加字符串

时间:2016-06-10 22:10:19

标签: python string format

我试图在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

1 个答案:

答案 0 :(得分:4)

只要您可以安全地评估WHERE字符串,即使where_condition不是字符串,这也会有效:

"SELECT ..." + bool(where_condition) * ("WHERE ...") + "GROUP ..."

我希望您能够非常小心地避免SQL注入。