1

I'm trying to build a query in python, I'm looking for an elegant way to append a WHERE condition in the middle of a string:

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 Answer 1

4

This will work as long as you can safely evaluate the WHERE string even if where_condition is not a string:

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

I hope you're being extremely careful to avoid SQL injection.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm using django and this is a function on my backend. Should I worry?
@GustavoReyes it depends on whether user input is used to construct that condition.
Then we're fine :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.