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

2👍

Why dont you use Django QuerySet, like this:

Book.objects.all().filter(keyword__in=['history','1800s']).values('name')

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])

0👍

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'
    params.append('%'+args['description']+'%')
if 'is_active' in args.keys():
    sql += ' AND is_active LIKE %s'
    params.append(args['is_active'])

… 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