Performing raw SQL queries

Django gives you two ways of performing raw SQL queries: you can useManager.raw() to perform raw queries and return model instances, oryou can avoid the model layer entirely and execute custom SQL directly.

Explore the ORM before using raw SQL!

The Django ORM provides many tools to express queries without writing rawSQL. For example:

警告

You should be very careful whenever you write raw SQL. Every time you useit, you should properly escape any parameters that the user can controlby using params in order to protect against SQL injection attacks.Please read more about SQL injection protection.

Performing raw queries

The raw() manager method can be used to perform raw SQL queries thatreturn model instances:

  • Manager.raw(raw_query, params=None, translations=None)
  • This method takes a raw SQL query, executes it, and returns adjango.db.models.query.RawQuerySet instance. This RawQuerySet instancecan be iterated over just like a normalQuerySet to provide object instances.

This is best illustrated with an example. Suppose you have the following model:

  1. class Person(models.Model):
  2. first_name = models.CharField(...)
  3. last_name = models.CharField(...)
  4. birth_date = models.DateField(...)

You could then execute custom SQL like so:

  1. >>> for p in Person.objects.raw('SELECT * FROM myapp_person'):
  2. ... print(p)
  3. John Smith
  4. Jane Jones

Of course, this example isn't very exciting — it's exactly the same asrunning Person.objects.all(). However, raw() has a bunch of otheroptions that make it very powerful.

Model table names

Where did the name of the Person table come from in that example?

By default, Django figures out a database table name by joining themodel's "app label" — the name you used in manage.py startapp — tothe model's class name, with an underscore between them. In the examplewe've assumed that the Person model lives in an app named myapp,so its table would be myapp_person.

For more details check out the documentation for thedb_table option, which also lets you manually set thedatabase table name.

警告

No checking is done on the SQL statement that is passed in to .raw().Django expects that the statement will return a set of rows from thedatabase, but does nothing to enforce that. If the query does notreturn rows, a (possibly cryptic) error will result.

警告

If you are performing queries on MySQL, note that MySQL's silent type coercionmay cause unexpected results when mixing types. If you query on a stringtype column, but with an integer value, MySQL will coerce the types of all valuesin the table to an integer before performing the comparison. For example, if yourtable contains the values 'abc', 'def' and you query for WHERE mycolumn=0,both rows will match. To prevent this, perform the correct typecastingbefore using the value in a query.

Mapping query fields to model fields

raw() automatically maps fields in the query to fields on the model.

The order of fields in your query doesn't matter. In other words, bothof the following queries work identically:

  1. >>> Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')
  2. ...
  3. >>> Person.objects.raw('SELECT last_name, birth_date, first_name, id FROM myapp_person')
  4. ...

Matching is done by name. This means that you can use SQL's AS clauses tomap fields in the query to model fields. So if you had some other table thathad Person data in it, you could easily map it into Person instances:

  1. >>> Person.objects.raw('''SELECT first AS first_name,
  2. ... last AS last_name,
  3. ... bd AS birth_date,
  4. ... pk AS id,
  5. ... FROM some_other_table''')

As long as the names match, the model instances will be created correctly.

Alternatively, you can map fields in the query to model fields using thetranslations argument to raw(). This is a dictionary mapping names offields in the query to names of fields on the model. For example, the abovequery could also be written:

  1. >>> name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
  2. >>> Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)

Index lookups

raw() supports indexing, so if you need only the first result you canwrite:

  1. >>> first_person = Person.objects.raw('SELECT * FROM myapp_person')[0]

However, the indexing and slicing are not performed at the database level. Ifyou have a large number of Person objects in your database, it is moreefficient to limit the query at the SQL level:

  1. >>> first_person = Person.objects.raw('SELECT * FROM myapp_person LIMIT 1')[0]

Deferring model fields

Fields may also be left out:

  1. >>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')

The Person objects returned by this query will be deferred model instances(see defer()). This means that thefields that are omitted from the query will be loaded on demand. For example:

  1. >>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
  2. ... print(p.first_name, # This will be retrieved by the original query
  3. ... p.last_name) # This will be retrieved on demand
  4. ...
  5. John Smith
  6. Jane Jones

From outward appearances, this looks like the query has retrieved boththe first name and last name. However, this example actually issued 3queries. Only the first names were retrieved by the raw() query — thelast names were both retrieved on demand when they were printed.

There is only one field that you can't leave out - the primary keyfield. Django uses the primary key to identify model instances, so itmust always be included in a raw query. An InvalidQuery exceptionwill be raised if you forget to include the primary key.

Adding annotations

You can also execute queries containing fields that aren't defined on themodel. For example, we could use PostgreSQL's age() function to get a listof people with their ages calculated by the database:

  1. >>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person')
  2. >>> for p in people:
  3. ... print("%s is %s." % (p.first_name, p.age))
  4. John is 37.
  5. Jane is 42.
  6. ...

You can often avoid using raw SQL to compute annotations by instead using aFunc() expression.

Passing parameters into raw()

If you need to perform parameterized queries, you can use the paramsargument to raw():

  1. >>> lname = 'Doe'
  2. >>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])

params is a list or dictionary of parameters. You'll use %splaceholders in the query string for a list, or %(key)splaceholders for a dictionary (where key is replaced by adictionary key, of course), regardless of your database engine. Suchplaceholders will be replaced with parameters from the paramsargument.

注解

Dictionary params are not supported with the SQLite backend; withthis backend, you must pass parameters as a list.

警告

Do not use string formatting on raw queries or quote placeholders in yourSQL strings!

It's tempting to write the above query as:

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

You might also think you should write your query like this (with quotesaround %s):

  1. >>> query = "SELECT * FROM myapp_person WHERE last_name = '%s'"

Don't make either of these mistakes.

As discussed in SQL injection protection, using the paramsargument and leaving the placeholders unquoted protects you from SQLinjection attacks, a common exploit where attackers inject arbitrarySQL into your database. If you use string interpolation or quote theplaceholder, you're at risk for SQL injection.

Executing custom SQL directly

Sometimes even Manager.raw() isn't quite enough: you might need toperform queries that don't map cleanly to models, or directly executeUPDATE, INSERT, or DELETE queries.

In these cases, you can always access the database directly, routing aroundthe model layer entirely.

The object django.db.connection represents the default databaseconnection. To use the database connection, call connection.cursor() toget a cursor object. Then, call cursor.execute(sql, [params]) to executethe SQL and cursor.fetchone() or cursor.fetchall() to return theresulting rows.

例如:

  1. from django.db import connection
  2.  
  3. def my_custom_sql(self):
  4. with connection.cursor() as cursor:
  5. cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
  6. cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
  7. row = cursor.fetchone()
  8.  
  9. return row

To protect against SQL injection, you must not include quotes around the %splaceholders in the SQL string.

Note that if you want to include literal percent signs in the query, you have todouble them in the case you are passing parameters:

  1. cursor.execute("SELECT foo FROM bar WHERE baz = '30%'")
  2. cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' AND id = %s", [self.id])

If you are using more than one database, you canuse django.db.connections to obtain the connection (and cursor) for aspecific database. django.db.connections is a dictionary-likeobject that allows you to retrieve a specific connection using itsalias:

  1. from django.db import connections
  2. with connections['my_db_alias'].cursor() as cursor:
  3. # Your code here...

By default, the Python DB API will return results without their field names,which means you end up with a list of values, rather than a dict. At asmall performance and memory cost, you can return results as a dict byusing something like this:

  1. def dictfetchall(cursor):
  2. "Return all rows from a cursor as a dict"
  3. columns = [col[0] for col in cursor.description]
  4. return [
  5. dict(zip(columns, row))
  6. for row in cursor.fetchall()
  7. ]

Another option is to use collections.namedtuple() from the Pythonstandard library. A namedtuple is a tuple-like object that has fieldsaccessible by attribute lookup; it's also indexable and iterable. Results areimmutable and accessible by field names or indices, which might be useful:

  1. from collections import namedtuple
  2.  
  3. def namedtuplefetchall(cursor):
  4. "Return all rows from a cursor as a namedtuple"
  5. desc = cursor.description
  6. nt_result = namedtuple('Result', [col[0] for col in desc])
  7. return [nt_result(*row) for row in cursor.fetchall()]

Here is an example of the difference between the three:

  1. >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
  2. >>> cursor.fetchall()
  3. ((54360982, None), (54360880, None))
  4.  
  5. >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
  6. >>> dictfetchall(cursor)
  7. [{'parent_id': None, 'id': 54360982}, {'parent_id': None, 'id': 54360880}]
  8.  
  9. >>> cursor.execute("SELECT id, parent_id FROM test LIMIT 2");
  10. >>> results = namedtuplefetchall(cursor)
  11. >>> results
  12. [Result(id=54360982, parent_id=None), Result(id=54360880, parent_id=None)]
  13. >>> results[0].id
  14. 54360982
  15. >>> results[0][0]
  16. 54360982

Connections and cursors

connection and cursor mostly implement the standard Python DB-APIdescribed in PEP 249 — except when it comes to transaction handling.

If you're not familiar with the Python DB-API, note that the SQL statement incursor.execute() uses placeholders, "%s", rather than addingparameters directly within the SQL. If you use this technique, the underlyingdatabase library will automatically escape your parameters as necessary.

Also note that Django expects the "%s" placeholder, not the "?"placeholder, which is used by the SQLite Python bindings. This is for the sakeof consistency and sanity.

Using a cursor as a context manager:

  1. with connection.cursor() as c:
  2. c.execute(...)

相当于:

  1. c = connection.cursor()
  2. try:
  3. c.execute(...)
  4. finally:
  5. c.close()

Calling stored procedures

  • CursorWrapper.callproc(procname, params=None, kparams=None)
  • Calls a database stored procedure with the given name. A sequence(params) or dictionary (kparams) of input parameters may beprovided. Most databases don't support kparams. Of Django's built-inbackends, only Oracle supports it.

For example, given this stored procedure in an Oracle database:

  1. CREATE PROCEDURE "TEST_PROCEDURE"(v_i INTEGER, v_text NVARCHAR2(10)) AS
  2. p_i INTEGER;
  3. p_text NVARCHAR2(10);
  4. BEGIN
  5. p_i := v_i;
  6. p_text := v_text;
  7. ...
  8. END;

This will call it:

  1. with connection.cursor() as cursor:
  2. cursor.callproc('test_procedure', [1, 'test'])