I’d like to be able to add a restriction to the query if user_id != None … for example:
"AND user_id = 5"
but I am not sure how to add this into the below function?
Thank you.
def get(id, user_id=None):
query = """SELECT *
FROM USERS
WHERE text LIKE %s AND
id = %s
"""
values = (search_text, id)
results = DB.get(query, values)
This way I can call:
get(5)
get(5,103524234) (contains user_id restriction)
As you see, the main difference wrt your original code is the small
ifblock in the middle, which enriches query string and values if needed. I also madevaluesa list, rather than a tuple, so it can be enriched with the more naturalappendrather than withwhich is arguably less readable – however, you can use it if you want to keep
valuesa tuple for some other reasons.edit: the OP now clarifies in a comment (!) that his original query has an ending
LIMITclause. In this case I would suggest a different approach, such as:You could do it in other ways, but keeping a list of query pieces in the proper order, enriching it as you go (e.g. by
insert), and joining it with some whitespace at the end, is a pretty general and usable approach.