user825904 user825904 - 1 year ago 129
Python Question

How can i insert parameters in raw sql in django python

I have this code

myquery = '''SELECT * from users
where id = 10 and
city = 20 and
state = 30'''

now i want to replace those with three variables like

var_id = bla
var_city = bla
var_state = bla

Answer Source

Use the params argument to raw():

var_id = 10
var_city = 20
var_state = 30

mymodel.objects.raw('''SELECT * from users 
                       where id = %s and
                       city = %s and 
                       state = %s ''', [var_id, var_city, var_state])

params is a list of parameters. You'll use %s placeholders in the query string (regardless of your database engine); they'll be replaced with parameters from the params list.

Important note from Django docs:

Warning Do not use string formatting on raw queries!

It's tempting to write the above query as:

>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
>>> Person.objects.raw(query)


Using the params list completely protects you from SQL injection attacks, a common exploit where attackers inject arbitrary SQL into your database. If you use string interpolation, sooner or later you'll fall victim to SQL injection. As long as you remember to always use the params list you'll be protected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download