This probably isn't a new question but I have not been able to find a decent solution after googling and digging through SO for a while. I want to have a conditional AND added to my WHERE clause based on if a variable is set or not.
I could put in a ternary into the string format but that does not seem like a good solution.
def run_query(start_date, end_date, value):
query = """
SELECT * FROM table WHERE value = %(value)s {date_clause}""".format(date_clause = "AND start_date >= %(start_date)s AND end_date <= %(end_date)s" if start_date is not None and end_date is not Null else "")
cursor.execute(query, {"start_date": None, "end_date": None, "value": value})