2009-12-20 10:46:58 +08:00
|
|
|
==========================
|
2008-08-24 06:25:40 +08:00
|
|
|
Performing raw SQL queries
|
|
|
|
==========================
|
|
|
|
|
2009-12-20 10:46:58 +08:00
|
|
|
.. currentmodule:: django.db.models
|
|
|
|
|
2010-08-20 03:27:44 +08:00
|
|
|
When the :doc:`model query APIs </topics/db/queries>` don't go far enough, you
|
2009-12-20 10:46:58 +08:00
|
|
|
can fall back to writing raw SQL. Django gives you two ways of performing raw
|
|
|
|
SQL queries: you can use :meth:`Manager.raw()` to `perform raw queries and
|
|
|
|
return model instances`__, or you can avoid the model layer entirely and
|
|
|
|
`execute custom SQL directly`__.
|
|
|
|
|
|
|
|
__ `performing raw queries`_
|
|
|
|
__ `executing custom SQL directly`_
|
|
|
|
|
2011-06-10 23:14:36 +08:00
|
|
|
.. _executing-raw-queries:
|
|
|
|
|
2009-12-20 10:46:58 +08:00
|
|
|
Performing raw queries
|
|
|
|
======================
|
|
|
|
|
|
|
|
The ``raw()`` manager method can be used to perform raw SQL queries that
|
|
|
|
return model instances:
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
.. method:: Manager.raw(raw_query, params=None, translations=None)
|
2009-12-20 10:46:58 +08:00
|
|
|
|
2010-02-24 21:57:02 +08:00
|
|
|
This method method takes a raw SQL query, executes it, and returns a
|
2013-01-01 21:12:42 +08:00
|
|
|
``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance
|
|
|
|
can be iterated over just like an normal QuerySet to provide object instances.
|
2009-12-20 10:46:58 +08:00
|
|
|
|
|
|
|
This is best illustrated with an example. Suppose you've got the following model::
|
|
|
|
|
|
|
|
class Person(models.Model):
|
|
|
|
first_name = models.CharField(...)
|
|
|
|
last_name = models.CharField(...)
|
|
|
|
birth_date = models.DateField(...)
|
|
|
|
|
|
|
|
You could then execute custom SQL like so::
|
|
|
|
|
2010-02-24 21:57:02 +08:00
|
|
|
>>> for p in Person.objects.raw('SELECT * FROM myapp_person'):
|
2012-04-29 00:02:01 +08:00
|
|
|
... print(p)
|
2010-02-24 21:57:02 +08:00
|
|
|
John Smith
|
|
|
|
Jane Jones
|
2009-12-20 10:46:58 +08:00
|
|
|
|
2011-03-15 03:49:53 +08:00
|
|
|
Of course, this example isn't very exciting -- it's exactly the same as
|
|
|
|
running ``Person.objects.all()``. However, ``raw()`` has a bunch of other
|
|
|
|
options that make it very powerful.
|
|
|
|
|
2009-12-20 10:46:58 +08:00
|
|
|
.. admonition:: Model table names
|
|
|
|
|
|
|
|
Where'd the name of the ``Person`` table come from in that example?
|
|
|
|
|
|
|
|
By default, Django figures out a database table name by joining the
|
|
|
|
model's "app label" -- the name you used in ``manage.py startapp`` -- to
|
|
|
|
the model's class name, with an underscore between them. In the example
|
|
|
|
we'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 the
|
|
|
|
:attr:`~Options.db_table` option, which also lets you manually set the
|
|
|
|
database table name.
|
|
|
|
|
2011-03-15 03:49:53 +08:00
|
|
|
.. warning::
|
|
|
|
|
|
|
|
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 the
|
|
|
|
database, but does nothing to enforce that. If the query does not
|
|
|
|
return rows, a (possibly cryptic) error will result.
|
2009-12-20 10:46:58 +08:00
|
|
|
|
|
|
|
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, both
|
|
|
|
of the following queries work identically::
|
|
|
|
|
|
|
|
>>> Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')
|
|
|
|
...
|
|
|
|
>>> Person.objects.raw('SELECT last_name, birth_date, first_name, id FROM myapp_person')
|
|
|
|
...
|
|
|
|
|
|
|
|
Matching is done by name. This means that you can use SQL's ``AS`` clauses to
|
|
|
|
map fields in the query to model fields. So if you had some other table that
|
|
|
|
had ``Person`` data in it, you could easily map it into ``Person`` instances::
|
|
|
|
|
|
|
|
>>> Person.objects.raw('''SELECT first AS first_name,
|
|
|
|
... last AS last_name,
|
|
|
|
... bd AS birth_date,
|
|
|
|
... pk as id,
|
2010-11-09 13:04:05 +08:00
|
|
|
... FROM some_other_table''')
|
2009-12-20 10:46:58 +08:00
|
|
|
|
|
|
|
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 the
|
|
|
|
``translations`` argument to ``raw()``. This is a dictionary mapping names of
|
|
|
|
fields in the query to names of fields on the model. For example, the above
|
|
|
|
query could also be written::
|
|
|
|
|
|
|
|
>>> name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
|
|
|
|
>>> Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)
|
|
|
|
|
2010-02-23 13:22:12 +08:00
|
|
|
Index lookups
|
|
|
|
-------------
|
|
|
|
|
|
|
|
``raw()`` supports indexing, so if you need only the first result you can
|
|
|
|
write::
|
|
|
|
|
|
|
|
>>> first_person = Person.objects.raw('SELECT * from myapp_person')[0]
|
|
|
|
|
|
|
|
However, the indexing and slicing are not performed at the database level. If
|
2010-02-23 14:04:06 +08:00
|
|
|
you have a big amount of ``Person`` objects in your database, it is more
|
2010-02-23 13:22:12 +08:00
|
|
|
efficient to limit the query at the SQL level::
|
|
|
|
|
|
|
|
>>> first_person = Person.objects.raw('SELECT * from myapp_person LIMIT 1')[0]
|
|
|
|
|
2009-12-20 10:46:58 +08:00
|
|
|
Deferring model fields
|
|
|
|
----------------------
|
|
|
|
|
|
|
|
Fields may also be left out::
|
|
|
|
|
2010-02-24 21:57:02 +08:00
|
|
|
>>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')
|
2009-12-20 10:46:58 +08:00
|
|
|
|
2010-08-07 22:26:07 +08:00
|
|
|
The ``Person`` objects returned by this query will be deferred model instances
|
2011-09-30 18:28:39 +08:00
|
|
|
(see :meth:`~django.db.models.query.QuerySet.defer()`). This means that the
|
|
|
|
fields that are omitted from the query will be loaded on demand. For example::
|
2009-12-20 10:46:58 +08:00
|
|
|
|
|
|
|
>>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
|
2012-04-29 00:02:01 +08:00
|
|
|
... print(p.first_name, # This will be retrieved by the original query
|
|
|
|
... p.last_name) # This will be retrieved on demand
|
2009-12-20 10:46:58 +08:00
|
|
|
...
|
|
|
|
John Smith
|
|
|
|
Jane Jones
|
|
|
|
|
|
|
|
From outward appearances, this looks like the query has retrieved both
|
|
|
|
the first name and last name. However, this example actually issued 3
|
|
|
|
queries. Only the first names were retrieved by the raw() query -- the
|
|
|
|
last names were both retrieved on demand when they were printed.
|
|
|
|
|
|
|
|
There is only one field that you can't leave out - the primary key
|
|
|
|
field. Django uses the primary key to identify model instances, so it
|
|
|
|
must always be included in a raw query. An ``InvalidQuery`` exception
|
|
|
|
will be raised if you forget to include the primary key.
|
|
|
|
|
|
|
|
Adding annotations
|
|
|
|
------------------
|
|
|
|
|
|
|
|
You can also execute queries containing fields that aren't defined on the
|
|
|
|
model. For example, we could use `PostgreSQL's age() function`__ to get a list
|
|
|
|
of people with their ages calculated by the database::
|
|
|
|
|
|
|
|
>>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person')
|
|
|
|
>>> for p in people:
|
2012-04-29 00:02:01 +08:00
|
|
|
... print("%s is %s." % (p.first_name, p.age))
|
2009-12-20 10:46:58 +08:00
|
|
|
John is 37.
|
|
|
|
Jane is 42.
|
|
|
|
...
|
|
|
|
|
|
|
|
__ http://www.postgresql.org/docs/8.4/static/functions-datetime.html
|
|
|
|
|
|
|
|
Passing parameters into ``raw()``
|
|
|
|
---------------------------------
|
|
|
|
|
|
|
|
If you need to perform parameterized queries, you can use the ``params``
|
|
|
|
argument to ``raw()``::
|
|
|
|
|
|
|
|
>>> lname = 'Doe'
|
|
|
|
>>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])
|
|
|
|
|
|
|
|
``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.
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
**Do not use string formatting on raw queries!**
|
|
|
|
|
|
|
|
It's tempting to write the above query as::
|
|
|
|
|
2009-12-21 09:53:39 +08:00
|
|
|
>>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
|
2009-12-20 10:46:58 +08:00
|
|
|
>>> Person.objects.raw(query)
|
|
|
|
|
|
|
|
**Don't.**
|
|
|
|
|
|
|
|
Using the ``params`` list completely protects you from `SQL injection
|
2009-12-21 09:53:39 +08:00
|
|
|
attacks`__, a common exploit where attackers inject arbitrary SQL into
|
2009-12-20 10:46:58 +08:00
|
|
|
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.
|
|
|
|
|
|
|
|
__ http://en.wikipedia.org/wiki/SQL_injection
|
|
|
|
|
2011-06-10 23:14:36 +08:00
|
|
|
.. _executing-custom-sql:
|
|
|
|
|
2009-12-20 10:46:58 +08:00
|
|
|
Executing custom SQL directly
|
|
|
|
=============================
|
|
|
|
|
|
|
|
Sometimes even :meth:`Manager.raw` isn't quite enough: you might need to
|
|
|
|
perform queries that don't map cleanly to models, or directly execute
|
|
|
|
``UPDATE``, ``INSERT``, or ``DELETE`` queries.
|
|
|
|
|
|
|
|
In these cases, you can always access the database directly, routing around
|
|
|
|
the model layer entirely.
|
|
|
|
|
|
|
|
The object ``django.db.connection`` represents the
|
2010-03-08 11:19:26 +08:00
|
|
|
default database connection, and ``django.db.transaction`` represents the
|
|
|
|
default database transaction. To use the database connection, call
|
2009-05-02 15:40:25 +08:00
|
|
|
``connection.cursor()`` to get a cursor object. Then, call
|
|
|
|
``cursor.execute(sql, [params])`` to execute the SQL and ``cursor.fetchone()``
|
|
|
|
or ``cursor.fetchall()`` to return the resulting rows. After performing a data
|
|
|
|
changing operation, you should then call
|
|
|
|
``transaction.commit_unless_managed()`` to ensure your changes are committed
|
|
|
|
to the database. If your query is purely a data retrieval operation, no commit
|
|
|
|
is required. For example::
|
2008-08-24 06:25:40 +08:00
|
|
|
|
2009-12-20 10:46:58 +08:00
|
|
|
def my_custom_sql():
|
2009-05-02 15:40:25 +08:00
|
|
|
from django.db import connection, transaction
|
2008-08-24 06:25:40 +08:00
|
|
|
cursor = connection.cursor()
|
2009-05-02 15:40:25 +08:00
|
|
|
|
|
|
|
# Data modifying operation - commit required
|
|
|
|
cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
|
|
|
|
transaction.commit_unless_managed()
|
|
|
|
|
|
|
|
# Data retrieval operation - no commit required
|
2008-08-24 06:25:40 +08:00
|
|
|
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
|
|
|
|
row = cursor.fetchone()
|
2009-05-02 15:40:25 +08:00
|
|
|
|
2008-08-24 06:25:40 +08:00
|
|
|
return row
|
|
|
|
|
2012-04-06 17:17:37 +08:00
|
|
|
If you are using :doc:`more than one database </topics/db/multi-db>`, you can
|
|
|
|
use ``django.db.connections`` to obtain the connection (and cursor) for a
|
2010-03-08 11:19:26 +08:00
|
|
|
specific database. ``django.db.connections`` is a dictionary-like
|
2011-05-30 20:11:10 +08:00
|
|
|
object that allows you to retrieve a specific connection using its
|
2010-03-08 11:19:26 +08:00
|
|
|
alias::
|
|
|
|
|
|
|
|
from django.db import connections
|
|
|
|
cursor = connections['my_db_alias'].cursor()
|
2011-02-12 02:23:55 +08:00
|
|
|
# Your code here...
|
|
|
|
transaction.commit_unless_managed(using='my_db_alias')
|
2010-03-08 11:19:26 +08:00
|
|
|
|
2011-09-11 13:37:55 +08:00
|
|
|
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 a small performance cost, you can return results as a
|
|
|
|
``dict`` by using something like this::
|
2012-09-20 04:39:14 +08:00
|
|
|
|
2011-09-11 13:37:55 +08:00
|
|
|
def dictfetchall(cursor):
|
|
|
|
"Returns all rows from a cursor as a dict"
|
|
|
|
desc = cursor.description
|
|
|
|
return [
|
|
|
|
dict(zip([col[0] for col in desc], row))
|
|
|
|
for row in cursor.fetchall()
|
|
|
|
]
|
|
|
|
|
|
|
|
Here is an example of the difference between the two::
|
|
|
|
|
|
|
|
>>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
|
|
|
|
>>> cursor.fetchall()
|
|
|
|
((54360982L, None), (54360880L, None))
|
2012-09-20 04:39:14 +08:00
|
|
|
|
2011-09-11 13:37:55 +08:00
|
|
|
>>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
|
|
|
|
>>> dictfetchall(cursor)
|
|
|
|
[{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}]
|
|
|
|
|
|
|
|
|
2009-06-17 21:47:39 +08:00
|
|
|
.. _transactions-and-raw-sql:
|
|
|
|
|
|
|
|
Transactions and raw SQL
|
|
|
|
------------------------
|
|
|
|
|
2011-02-12 21:03:34 +08:00
|
|
|
When you make a raw SQL call, Django will automatically mark the
|
|
|
|
current transaction as dirty. You must then ensure that the
|
|
|
|
transaction containing those calls is closed correctly. See :ref:`the
|
|
|
|
notes on the requirements of Django's transaction handling
|
|
|
|
<topics-db-transactions-requirements>` for more details.
|
2009-06-17 21:47:39 +08:00
|
|
|
|
|
|
|
Connections and cursors
|
|
|
|
-----------------------
|
|
|
|
|
2011-09-05 05:17:30 +08:00
|
|
|
``connection`` and ``cursor`` mostly implement the standard Python DB-API
|
|
|
|
described in :pep:`249` (except when it comes to :doc:`transaction handling
|
|
|
|
</topics/db/transactions>`). If you're not familiar with the Python DB-API, note
|
|
|
|
that the SQL statement in ``cursor.execute()`` uses placeholders, ``"%s"``,
|
|
|
|
rather than adding parameters directly within the SQL. If you use this
|
|
|
|
technique, the underlying database library will automatically add quotes and
|
|
|
|
escaping to your parameter(s) 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 sake of consistency and sanity.)
|