Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I insert parameters in raw SQL in Django Python

Tags:

python

django

I have this code

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

I want to replace those with three variables like

var_id = bla
var_city = bla
var_state = bla
like image 288
Mirage Avatar asked Nov 02 '12 05:11

Mirage


People also ask

Can we use SQL with Django?

Django officially supports five database management systems: PostgreSQL, MariaDB, MySQL, Oracle, and SQLite (Django, 2020). Some third parties provide backends for other DBMSs, such as CockroachDB, Firebird, and Microsoft SQL Server.

What is a raw query in SQL?

Raw SQL, sometimes also called native SQL, is the most basic, most low-level form of database interaction. You tell the database what to do in the language of the database. Most developers should know basics of SQL. This means how to CREATE tables and views, how to SELECT and JOIN data, how to UPDATE and DELETE data.

Does Django ORM support subquery?

¶ Django allows using SQL subqueries.

What is QuerySet in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.


2 Answers

You can also use dictionaries and variables in your queries as so:

my_dict = {
   'id': 10,
   'city': 20,
   'state': 30
} 

mymodel.objects.raw('''SELECT * from users 
                       where id = %(id)s and
                       city = %(city)s and 
                       state = %(state)s ''', my_dict)

You can read more up on it here: https://docs.djangoproject.com/en/1.10/topics/db/sql/#passing-parameters-into-raw

like image 103
Nick Lucas Avatar answered Oct 07 '22 16:10

Nick Lucas


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)

Don't.

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.

like image 38
K Z Avatar answered Oct 07 '22 17:10

K Z