sql.txt 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. ==========================
  2. Performing raw SQL queries
  3. ==========================
  4. .. currentmodule:: django.db.models
  5. When the :doc:`model query APIs </topics/db/queries>` don't go far enough, you
  6. can fall back to writing raw SQL. Django gives you two ways of performing raw
  7. SQL queries: you can use :meth:`Manager.raw()` to `perform raw queries and
  8. return model instances`__, or you can avoid the model layer entirely and
  9. `execute custom SQL directly`__.
  10. __ `performing raw queries`_
  11. __ `executing custom SQL directly`_
  12. .. _executing-raw-queries:
  13. Performing raw queries
  14. ======================
  15. The ``raw()`` manager method can be used to perform raw SQL queries that
  16. return model instances:
  17. .. method:: Manager.raw(raw_query, params=None, translations=None)
  18. This method method takes a raw SQL query, executes it, and returns a
  19. ``django.db.models.query.RawQuerySet`` instance. This ``RawQuerySet`` instance
  20. can be iterated over just like an normal QuerySet to provide object instances.
  21. This is best illustrated with an example. Suppose you've got the following model::
  22. class Person(models.Model):
  23. first_name = models.CharField(...)
  24. last_name = models.CharField(...)
  25. birth_date = models.DateField(...)
  26. You could then execute custom SQL like so::
  27. >>> for p in Person.objects.raw('SELECT * FROM myapp_person'):
  28. ... print(p)
  29. John Smith
  30. Jane Jones
  31. Of course, this example isn't very exciting -- it's exactly the same as
  32. running ``Person.objects.all()``. However, ``raw()`` has a bunch of other
  33. options that make it very powerful.
  34. .. admonition:: Model table names
  35. Where'd the name of the ``Person`` table come from in that example?
  36. By default, Django figures out a database table name by joining the
  37. model's "app label" -- the name you used in ``manage.py startapp`` -- to
  38. the model's class name, with an underscore between them. In the example
  39. we've assumed that the ``Person`` model lives in an app named ``myapp``,
  40. so its table would be ``myapp_person``.
  41. For more details check out the documentation for the
  42. :attr:`~Options.db_table` option, which also lets you manually set the
  43. database table name.
  44. .. warning::
  45. No checking is done on the SQL statement that is passed in to ``.raw()``.
  46. Django expects that the statement will return a set of rows from the
  47. database, but does nothing to enforce that. If the query does not
  48. return rows, a (possibly cryptic) error will result.
  49. Mapping query fields to model fields
  50. ------------------------------------
  51. ``raw()`` automatically maps fields in the query to fields on the model.
  52. The order of fields in your query doesn't matter. In other words, both
  53. of the following queries work identically::
  54. >>> Person.objects.raw('SELECT id, first_name, last_name, birth_date FROM myapp_person')
  55. ...
  56. >>> Person.objects.raw('SELECT last_name, birth_date, first_name, id FROM myapp_person')
  57. ...
  58. Matching is done by name. This means that you can use SQL's ``AS`` clauses to
  59. map fields in the query to model fields. So if you had some other table that
  60. had ``Person`` data in it, you could easily map it into ``Person`` instances::
  61. >>> Person.objects.raw('''SELECT first AS first_name,
  62. ... last AS last_name,
  63. ... bd AS birth_date,
  64. ... pk as id,
  65. ... FROM some_other_table''')
  66. As long as the names match, the model instances will be created correctly.
  67. Alternatively, you can map fields in the query to model fields using the
  68. ``translations`` argument to ``raw()``. This is a dictionary mapping names of
  69. fields in the query to names of fields on the model. For example, the above
  70. query could also be written::
  71. >>> name_map = {'first': 'first_name', 'last': 'last_name', 'bd': 'birth_date', 'pk': 'id'}
  72. >>> Person.objects.raw('SELECT * FROM some_other_table', translations=name_map)
  73. Index lookups
  74. -------------
  75. ``raw()`` supports indexing, so if you need only the first result you can
  76. write::
  77. >>> first_person = Person.objects.raw('SELECT * from myapp_person')[0]
  78. However, the indexing and slicing are not performed at the database level. If
  79. you have a big amount of ``Person`` objects in your database, it is more
  80. efficient to limit the query at the SQL level::
  81. >>> first_person = Person.objects.raw('SELECT * from myapp_person LIMIT 1')[0]
  82. Deferring model fields
  83. ----------------------
  84. Fields may also be left out::
  85. >>> people = Person.objects.raw('SELECT id, first_name FROM myapp_person')
  86. The ``Person`` objects returned by this query will be deferred model instances
  87. (see :meth:`~django.db.models.query.QuerySet.defer()`). This means that the
  88. fields that are omitted from the query will be loaded on demand. For example::
  89. >>> for p in Person.objects.raw('SELECT id, first_name FROM myapp_person'):
  90. ... print(p.first_name, # This will be retrieved by the original query
  91. ... p.last_name) # This will be retrieved on demand
  92. ...
  93. John Smith
  94. Jane Jones
  95. From outward appearances, this looks like the query has retrieved both
  96. the first name and last name. However, this example actually issued 3
  97. queries. Only the first names were retrieved by the raw() query -- the
  98. last names were both retrieved on demand when they were printed.
  99. There is only one field that you can't leave out - the primary key
  100. field. Django uses the primary key to identify model instances, so it
  101. must always be included in a raw query. An ``InvalidQuery`` exception
  102. will be raised if you forget to include the primary key.
  103. Adding annotations
  104. ------------------
  105. You can also execute queries containing fields that aren't defined on the
  106. model. For example, we could use `PostgreSQL's age() function`__ to get a list
  107. of people with their ages calculated by the database::
  108. >>> people = Person.objects.raw('SELECT *, age(birth_date) AS age FROM myapp_person')
  109. >>> for p in people:
  110. ... print("%s is %s." % (p.first_name, p.age))
  111. John is 37.
  112. Jane is 42.
  113. ...
  114. __ http://www.postgresql.org/docs/8.4/static/functions-datetime.html
  115. Passing parameters into ``raw()``
  116. ---------------------------------
  117. If you need to perform parameterized queries, you can use the ``params``
  118. argument to ``raw()``::
  119. >>> lname = 'Doe'
  120. >>> Person.objects.raw('SELECT * FROM myapp_person WHERE last_name = %s', [lname])
  121. ``params`` is a list of parameters. You'll use ``%s`` placeholders in the
  122. query string (regardless of your database engine); they'll be replaced with
  123. parameters from the ``params`` list.
  124. .. warning::
  125. **Do not use string formatting on raw queries!**
  126. It's tempting to write the above query as::
  127. >>> query = 'SELECT * FROM myapp_person WHERE last_name = %s' % lname
  128. >>> Person.objects.raw(query)
  129. **Don't.**
  130. Using the ``params`` list completely protects you from `SQL injection
  131. attacks`__, a common exploit where attackers inject arbitrary SQL into
  132. your database. If you use string interpolation, sooner or later you'll
  133. fall victim to SQL injection. As long as you remember to always use the
  134. ``params`` list you'll be protected.
  135. __ http://en.wikipedia.org/wiki/SQL_injection
  136. .. _executing-custom-sql:
  137. Executing custom SQL directly
  138. =============================
  139. Sometimes even :meth:`Manager.raw` isn't quite enough: you might need to
  140. perform queries that don't map cleanly to models, or directly execute
  141. ``UPDATE``, ``INSERT``, or ``DELETE`` queries.
  142. In these cases, you can always access the database directly, routing around
  143. the model layer entirely.
  144. The object ``django.db.connection`` represents the default database
  145. connection. To use the database connection, call ``connection.cursor()`` to
  146. get a cursor object. Then, call ``cursor.execute(sql, [params])`` to execute
  147. the SQL and ``cursor.fetchone()`` or ``cursor.fetchall()`` to return the
  148. resulting rows.
  149. For example::
  150. from django.db import connection
  151. def my_custom_sql():
  152. cursor = connection.cursor()
  153. cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
  154. cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
  155. row = cursor.fetchone()
  156. return row
  157. .. versionchanged:: 1.6
  158. In Django 1.5 and earlier, after performing a data changing operation, you
  159. had to call ``transaction.commit_unless_managed()`` to ensure your changes
  160. were committed to the database. Since Django now defaults to database-level
  161. autocommit, this isn't necessary any longer.
  162. If you are using :doc:`more than one database </topics/db/multi-db>`, you can
  163. use ``django.db.connections`` to obtain the connection (and cursor) for a
  164. specific database. ``django.db.connections`` is a dictionary-like
  165. object that allows you to retrieve a specific connection using its
  166. alias::
  167. from django.db import connections
  168. cursor = connections['my_db_alias'].cursor()
  169. # Your code here...
  170. By default, the Python DB API will return results without their field
  171. names, which means you end up with a ``list`` of values, rather than a
  172. ``dict``. At a small performance cost, you can return results as a
  173. ``dict`` by using something like this::
  174. def dictfetchall(cursor):
  175. "Returns all rows from a cursor as a dict"
  176. desc = cursor.description
  177. return [
  178. dict(zip([col[0] for col in desc], row))
  179. for row in cursor.fetchall()
  180. ]
  181. Here is an example of the difference between the two::
  182. >>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
  183. >>> cursor.fetchall()
  184. ((54360982L, None), (54360880L, None))
  185. >>> cursor.execute("SELECT id, parent_id from test LIMIT 2");
  186. >>> dictfetchall(cursor)
  187. [{'parent_id': None, 'id': 54360982L}, {'parent_id': None, 'id': 54360880L}]
  188. Connections and cursors
  189. -----------------------
  190. ``connection`` and ``cursor`` mostly implement the standard Python DB-API
  191. described in :pep:`249` — except when it comes to :doc:`transaction handling
  192. </topics/db/transactions>`.
  193. If you're not familiar with the Python DB-API, note that the SQL statement in
  194. ``cursor.execute()`` uses placeholders, ``"%s"``, rather than adding
  195. parameters directly within the SQL. If you use this technique, the underlying
  196. database library will automatically escape your parameters as necessary.
  197. Also note that Django expects the ``"%s"`` placeholder, *not* the ``"?"``
  198. placeholder, which is used by the SQLite Python bindings. This is for the sake
  199. of consistency and sanity.