[Answered ]-Django: raw SQL queries with a dynamic number of variables


Why dont you use Django QuerySet, like this:


Another possible solution using RAW SQL, coud be:

keywords = []
SQL = 'SELECT appname_book.name AS name FROM appname_book WHERE 1=1 '
SQL += ' '.join(['AND keyword=%s' for _ in params])


Sure, you could do something like this to dynamically generate a raw SQL query

sql = 'SELECT id FROM table WHERE 1 = 1'
params = []

if 'description' in args.keys():
    sql += ' AND description LIKE %s'
if 'is_active' in args.keys():
    sql += ' AND is_active LIKE %s'

… you can put as many "ifs" you want to construct the query

with connections['default'].cursor() as cursor:
    cursor.execute(sql, params)

This way would still be completely safe against SQL Injections vulnerability

Leave a comment