optimization.txt 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. ============================
  2. Database access optimization
  3. ============================
  4. Django's database layer provides various ways to help developers get the most
  5. out of their databases. This document gathers together links to the relevant
  6. documentation, and adds various tips, organized under a number of headings that
  7. outline the steps to take when attempting to optimize your database usage.
  8. Profile first
  9. =============
  10. As general programming practice, this goes without saying. Find out :ref:`what
  11. queries you are doing and what they are costing you
  12. <faq-see-raw-sql-queries>`. You may also want to use an external project like
  13. django-debug-toolbar_, or a tool that monitors your database directly.
  14. Remember that you may be optimizing for speed or memory or both, depending on
  15. your requirements. Sometimes optimizing for one will be detrimental to the
  16. other, but sometimes they will help each other. Also, work that is done by the
  17. database process might not have the same cost (to you) as the same amount of
  18. work done in your Python process. It is up to you to decide what your
  19. priorities are, where the balance must lie, and profile all of these as required
  20. since this will depend on your application and server.
  21. With everything that follows, remember to profile after every change to ensure
  22. that the change is a benefit, and a big enough benefit given the decrease in
  23. readability of your code. **All** of the suggestions below come with the caveat
  24. that in your circumstances the general principle might not apply, or might even
  25. be reversed.
  26. .. _django-debug-toolbar: https://github.com/django-debug-toolbar/django-debug-toolbar/
  27. Use standard DB optimization techniques
  28. =======================================
  29. ...including:
  30. * Indexes. This is a number one priority, *after* you have determined from
  31. profiling what indexes should be added. Use
  32. :attr:`django.db.models.Field.db_index` or
  33. :attr:`Meta.index_together <django.db.models.Options.index_together>` to add
  34. these from Django.
  35. * Appropriate use of field types.
  36. We will assume you have done the obvious things above. The rest of this document
  37. focuses on how to use Django in such a way that you are not doing unnecessary
  38. work. This document also does not address other optimization techniques that
  39. apply to all expensive operations, such as :doc:`general purpose caching
  40. </topics/cache>`.
  41. Understand QuerySets
  42. ====================
  43. Understanding :doc:`QuerySets </ref/models/querysets>` is vital to getting good
  44. performance with simple code. In particular:
  45. Understand QuerySet evaluation
  46. ------------------------------
  47. To avoid performance problems, it is important to understand:
  48. * that :ref:`QuerySets are lazy <querysets-are-lazy>`.
  49. * when :ref:`they are evaluated <when-querysets-are-evaluated>`.
  50. * how :ref:`the data is held in memory <caching-and-querysets>`.
  51. Understand cached attributes
  52. ----------------------------
  53. As well as caching of the whole ``QuerySet``, there is caching of the result of
  54. attributes on ORM objects. In general, attributes that are not callable will be
  55. cached. For example, assuming the :ref:`example Weblog models
  56. <queryset-model-example>`::
  57. >>> entry = Entry.objects.get(id=1)
  58. >>> entry.blog # Blog object is retrieved at this point
  59. >>> entry.blog # cached version, no DB access
  60. But in general, callable attributes cause DB lookups every time::
  61. >>> entry = Entry.objects.get(id=1)
  62. >>> entry.authors.all() # query performed
  63. >>> entry.authors.all() # query performed again
  64. Be careful when reading template code - the template system does not allow use
  65. of parentheses, but will call callables automatically, hiding the above
  66. distinction.
  67. Be careful with your own custom properties - it is up to you to implement
  68. caching when required, for example using the
  69. :class:`~django.utils.functional.cached_property` decorator.
  70. Use the ``with`` template tag
  71. -----------------------------
  72. To make use of the caching behavior of ``QuerySet``, you may need to use the
  73. :ttag:`with` template tag.
  74. Use ``iterator()``
  75. ------------------
  76. When you have a lot of objects, the caching behavior of the ``QuerySet`` can
  77. cause a large amount of memory to be used. In this case,
  78. :meth:`~django.db.models.query.QuerySet.iterator()` may help.
  79. Do database work in the database rather than in Python
  80. ======================================================
  81. For instance:
  82. * At the most basic level, use :ref:`filter and exclude <queryset-api>` to do
  83. filtering in the database.
  84. * Use :class:`F expressions <django.db.models.F>` to filter
  85. based on other fields within the same model.
  86. * Use :doc:`annotate to do aggregation in the database
  87. </topics/db/aggregation>`.
  88. If these aren't enough to generate the SQL you need:
  89. Use ``QuerySet.extra()``
  90. ------------------------
  91. A less portable but more powerful method is
  92. :meth:`~django.db.models.query.QuerySet.extra()`, which allows some SQL to be
  93. explicitly added to the query. If that still isn't powerful enough:
  94. Use raw SQL
  95. -----------
  96. Write your own :doc:`custom SQL to retrieve data or populate models
  97. </topics/db/sql>`. Use ``django.db.connection.queries`` to find out what Django
  98. is writing for you and start from there.
  99. Retrieve individual objects using a unique, indexed column
  100. ==========================================================
  101. There are two reasons to use a column with
  102. :attr:`~django.db.models.Field.unique` or
  103. :attr:`~django.db.models.Field.db_index` when using
  104. :meth:`~django.db.models.query.QuerySet.get` to retrieve individual objects.
  105. First, the query will be quicker because of the underlying database index.
  106. Also, the query could run much slower if multiple objects match the lookup;
  107. having a unique constraint on the column guarantees this will never happen.
  108. So using the :ref:`example Weblog models <queryset-model-example>`::
  109. >>> entry = Entry.objects.get(id=10)
  110. will be quicker than:
  111. >>> entry = Entry.object.get(headline="News Item Title")
  112. because ``id`` is indexed by the database and is guaranteed to be unique.
  113. Doing the following is potentially quite slow:
  114. >>> entry = Entry.objects.get(headline__startswith="News")
  115. First of all, ``headline`` is not indexed, which will make the underlying
  116. database fetch slower.
  117. Second, the lookup doesn't guarantee that only one object will be returned.
  118. If the query matches more than one object, it will retrieve and transfer all of
  119. them from the database. This penalty could be substantial if hundreds or
  120. thousands of records are returned. The penalty will be compounded if the
  121. database lives on a separate server, where network overhead and latency also
  122. play a factor.
  123. Retrieve everything at once if you know you will need it
  124. ========================================================
  125. Hitting the database multiple times for different parts of a single 'set' of
  126. data that you will need all parts of is, in general, less efficient than
  127. retrieving it all in one query. This is particularly important if you have a
  128. query that is executed in a loop, and could therefore end up doing many database
  129. queries, when only one was needed. So:
  130. Use ``QuerySet.select_related()`` and ``prefetch_related()``
  131. ------------------------------------------------------------
  132. Understand :meth:`~django.db.models.query.QuerySet.select_related` and
  133. :meth:`~django.db.models.query.QuerySet.prefetch_related` thoroughly, and use
  134. them:
  135. * in view code,
  136. * and in :doc:`managers and default managers </topics/db/managers>` where
  137. appropriate. Be aware when your manager is and is not used; sometimes this is
  138. tricky so don't make assumptions.
  139. Don't retrieve things you don't need
  140. ====================================
  141. Use ``QuerySet.values()`` and ``values_list()``
  142. -----------------------------------------------
  143. When you just want a ``dict`` or ``list`` of values, and don't need ORM model
  144. objects, make appropriate usage of
  145. :meth:`~django.db.models.query.QuerySet.values()`.
  146. These can be useful for replacing model objects in template code - as long as
  147. the dicts you supply have the same attributes as those used in the template,
  148. you are fine.
  149. Use ``QuerySet.defer()`` and ``only()``
  150. ---------------------------------------
  151. Use :meth:`~django.db.models.query.QuerySet.defer()` and
  152. :meth:`~django.db.models.query.QuerySet.only()` if there are database columns
  153. you know that you won't need (or won't need in most cases) to avoid loading
  154. them. Note that if you *do* use them, the ORM will have to go and get them in
  155. a separate query, making this a pessimization if you use it inappropriately.
  156. Also, be aware that there is some (small extra) overhead incurred inside
  157. Django when constructing a model with deferred fields. Don't be too aggressive
  158. in deferring fields without profiling as the database has to read most of the
  159. non-text, non-VARCHAR data from the disk for a single row in the results, even
  160. if it ends up only using a few columns. The ``defer()`` and ``only()`` methods
  161. are most useful when you can avoid loading a lot of text data or for fields
  162. that might take a lot of processing to convert back to Python. As always,
  163. profile first, then optimize.
  164. Use QuerySet.count()
  165. --------------------
  166. ...if you only want the count, rather than doing ``len(queryset)``.
  167. Use QuerySet.exists()
  168. ---------------------
  169. ...if you only want to find out if at least one result exists, rather than ``if
  170. queryset``.
  171. But:
  172. .. _overuse_of_count_and_exists:
  173. Don't overuse ``count()`` and ``exists()``
  174. ------------------------------------------
  175. If you are going to need other data from the QuerySet, just evaluate it.
  176. For example, assuming an Email model that has a ``body`` attribute and a
  177. many-to-many relation to User, the following template code is optimal:
  178. .. code-block:: html+django
  179. {% if display_inbox %}
  180. {% with emails=user.emails.all %}
  181. {% if emails %}
  182. <p>You have {{ emails|length }} email(s)</p>
  183. {% for email in emails %}
  184. <p>{{ email.body }}</p>
  185. {% endfor %}
  186. {% else %}
  187. <p>No messages today.</p>
  188. {% endif %}
  189. {% endwith %}
  190. {% endif %}
  191. It is optimal because:
  192. 1. Since QuerySets are lazy, this does no database queries if 'display_inbox'
  193. is False.
  194. #. Use of :ttag:`with` means that we store ``user.emails.all`` in a variable
  195. for later use, allowing its cache to be re-used.
  196. #. The line ``{% if emails %}`` causes ``QuerySet.__bool__()`` to be called,
  197. which causes the ``user.emails.all()`` query to be run on the database, and
  198. at the least the first line to be turned into an ORM object. If there aren't
  199. any results, it will return False, otherwise True.
  200. #. The use of ``{{ emails|length }}`` calls ``QuerySet.__len__()``, filling
  201. out the rest of the cache without doing another query.
  202. #. The :ttag:`for` loop iterates over the already filled cache.
  203. In total, this code does either one or zero database queries. The only
  204. deliberate optimization performed is the use of the :ttag:`with` tag. Using
  205. ``QuerySet.exists()`` or ``QuerySet.count()`` at any point would cause
  206. additional queries.
  207. Use ``QuerySet.update()`` and ``delete()``
  208. ------------------------------------------
  209. Rather than retrieve a load of objects, set some values, and save them
  210. individual, use a bulk SQL UPDATE statement, via :ref:`QuerySet.update()
  211. <topics-db-queries-update>`. Similarly, do :ref:`bulk deletes
  212. <topics-db-queries-delete>` where possible.
  213. Note, however, that these bulk update methods cannot call the ``save()`` or
  214. ``delete()`` methods of individual instances, which means that any custom
  215. behavior you have added for these methods will not be executed, including
  216. anything driven from the normal database object :doc:`signals </ref/signals>`.
  217. Use foreign key values directly
  218. -------------------------------
  219. If you only need a foreign key value, use the foreign key value that is already on
  220. the object you've got, rather than getting the whole related object and taking
  221. its primary key. i.e. do::
  222. entry.blog_id
  223. instead of::
  224. entry.blog.id
  225. Don't order results if you don't care
  226. -------------------------------------
  227. Ordering is not free; each field to order by is an operation the database must
  228. perform. If a model has a default ordering (:attr:`Meta.ordering
  229. <django.db.models.Options.ordering>`) and you don't need it, remove
  230. it on a ``QuerySet`` by calling
  231. :meth:`~django.db.models.query.QuerySet.order_by()` with no parameters.
  232. Adding an index to your database may help to improve ordering performance.
  233. Insert in bulk
  234. ==============
  235. When creating objects, where possible, use the
  236. :meth:`~django.db.models.query.QuerySet.bulk_create()` method to reduce the
  237. number of SQL queries. For example::
  238. Entry.objects.bulk_create([
  239. Entry(headline="Python 3.0 Released"),
  240. Entry(headline="Python 3.1 Planned")
  241. ])
  242. ...is preferable to::
  243. Entry.objects.create(headline="Python 3.0 Released")
  244. Entry.objects.create(headline="Python 3.1 Planned")
  245. Note that there are a number of :meth:`caveats to this method
  246. <django.db.models.query.QuerySet.bulk_create>`, so make sure it's appropriate
  247. for your use case.
  248. This also applies to :class:`ManyToManyFields
  249. <django.db.models.ManyToManyField>`, so doing::
  250. my_band.members.add(me, my_friend)
  251. ...is preferable to::
  252. my_band.members.add(me)
  253. my_band.members.add(my_friend)
  254. ...where ``Bands`` and ``Artists`` have a many-to-many relationship.