optimization.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 <faq-see-raw-sql-queries>`.
  12. Use :meth:`.QuerySet.explain` to understand how specific ``QuerySet``\s are
  13. executed by your database. You may also want to use an external project like
  14. django-debug-toolbar_, or a tool that monitors your database directly.
  15. Remember that you may be optimizing for speed or memory or both, depending on
  16. your requirements. Sometimes optimizing for one will be detrimental to the
  17. other, but sometimes they will help each other. Also, work that is done by the
  18. database process might not have the same cost (to you) as the same amount of
  19. work done in your Python process. It is up to you to decide what your
  20. priorities are, where the balance must lie, and profile all of these as required
  21. since this will depend on your application and server.
  22. With everything that follows, remember to profile after every change to ensure
  23. that the change is a benefit, and a big enough benefit given the decrease in
  24. readability of your code. **All** of the suggestions below come with the caveat
  25. that in your circumstances the general principle might not apply, or might even
  26. be reversed.
  27. .. _django-debug-toolbar: https://github.com/jazzband/django-debug-toolbar/
  28. Use standard DB optimization techniques
  29. =======================================
  30. ...including:
  31. * Indexes_. This is a number one priority, *after* you have determined from
  32. profiling what indexes should be added. Use
  33. :attr:`Meta.indexes <django.db.models.Options.indexes>` or
  34. :attr:`Field.db_index <django.db.models.Field.db_index>` to add these from
  35. Django. Consider adding indexes to fields that you frequently query using
  36. :meth:`~django.db.models.query.QuerySet.filter()`,
  37. :meth:`~django.db.models.query.QuerySet.exclude()`,
  38. :meth:`~django.db.models.query.QuerySet.order_by()`, etc. as indexes may help
  39. to speed up lookups. Note that determining the best indexes is a complex
  40. database-dependent topic that will depend on your particular application.
  41. The overhead of maintaining an index may outweigh any gains in query speed.
  42. .. _Indexes: https://en.wikipedia.org/wiki/Database_index
  43. * Appropriate use of field types.
  44. We will assume you have done the things listed above. The rest of this document
  45. focuses on how to use Django in such a way that you are not doing unnecessary
  46. work. This document also does not address other optimization techniques that
  47. apply to all expensive operations, such as :doc:`general purpose caching
  48. </topics/cache>`.
  49. Understand ``QuerySet``\s
  50. =========================
  51. Understanding :doc:`QuerySets </ref/models/querysets>` is vital to getting good
  52. performance with simple code. In particular:
  53. Understand ``QuerySet`` evaluation
  54. ----------------------------------
  55. To avoid performance problems, it is important to understand:
  56. * that :ref:`QuerySets are lazy <querysets-are-lazy>`.
  57. * when :ref:`they are evaluated <when-querysets-are-evaluated>`.
  58. * how :ref:`the data is held in memory <caching-and-querysets>`.
  59. Understand cached attributes
  60. ----------------------------
  61. As well as caching of the whole ``QuerySet``, there is caching of the result of
  62. attributes on ORM objects. In general, attributes that are not callable will be
  63. cached. For example, assuming the :ref:`example blog models
  64. <queryset-model-example>`:
  65. .. code-block:: pycon
  66. >>> entry = Entry.objects.get(id=1)
  67. >>> entry.blog # Blog object is retrieved at this point
  68. >>> entry.blog # cached version, no DB access
  69. But in general, callable attributes cause DB lookups every time:
  70. .. code-block:: pycon
  71. >>> entry = Entry.objects.get(id=1)
  72. >>> entry.authors.all() # query performed
  73. >>> entry.authors.all() # query performed again
  74. Be careful when reading template code - the template system does not allow use
  75. of parentheses, but will call callables automatically, hiding the above
  76. distinction.
  77. Be careful with your own custom properties - it is up to you to implement
  78. caching when required, for example using the
  79. :class:`~django.utils.functional.cached_property` decorator.
  80. Use the ``with`` template tag
  81. -----------------------------
  82. To make use of the caching behavior of ``QuerySet``, you may need to use the
  83. :ttag:`with` template tag.
  84. Use ``iterator()``
  85. ------------------
  86. When you have a lot of objects, the caching behavior of the ``QuerySet`` can
  87. cause a large amount of memory to be used. In this case,
  88. :meth:`~django.db.models.query.QuerySet.iterator()` may help.
  89. Use ``explain()``
  90. -----------------
  91. :meth:`.QuerySet.explain` gives you detailed information about how the database
  92. executes a query, including indexes and joins that are used. These details may
  93. help you find queries that could be rewritten more efficiently, or identify
  94. indexes that could be added to improve performance.
  95. Do database work in the database rather than in Python
  96. ======================================================
  97. For instance:
  98. * At the most basic level, use :ref:`filter and exclude <queryset-api>` to do
  99. filtering in the database.
  100. * Use :class:`F expressions <django.db.models.F>` to filter
  101. based on other fields within the same model.
  102. * Use :doc:`annotate to do aggregation in the database
  103. </topics/db/aggregation>`.
  104. If these aren't enough to generate the SQL you need:
  105. Use ``RawSQL``
  106. --------------
  107. A less portable but more powerful method is the
  108. :class:`~django.db.models.expressions.RawSQL` expression, which allows some SQL
  109. to be explicitly added to the query. If that still isn't powerful enough:
  110. Use raw SQL
  111. -----------
  112. Write your own :doc:`custom SQL to retrieve data or populate models
  113. </topics/db/sql>`. Use ``django.db.connection.queries`` to find out what Django
  114. is writing for you and start from there.
  115. Retrieve individual objects using a unique, indexed column
  116. ==========================================================
  117. There are two reasons to use a column with
  118. :attr:`~django.db.models.Field.unique` or
  119. :attr:`~django.db.models.Field.db_index` when using
  120. :meth:`~django.db.models.query.QuerySet.get` to retrieve individual objects.
  121. First, the query will be quicker because of the underlying database index.
  122. Also, the query could run much slower if multiple objects match the lookup;
  123. having a unique constraint on the column guarantees this will never happen.
  124. So using the :ref:`example blog models <queryset-model-example>`:
  125. .. code-block:: pycon
  126. >>> entry = Entry.objects.get(id=10)
  127. will be quicker than:
  128. .. code-block:: pycon
  129. >>> entry = Entry.objects.get(headline="News Item Title")
  130. because ``id`` is indexed by the database and is guaranteed to be unique.
  131. Doing the following is potentially quite slow:
  132. .. code-block:: pycon
  133. >>> entry = Entry.objects.get(headline__startswith="News")
  134. First of all, ``headline`` is not indexed, which will make the underlying
  135. database fetch slower.
  136. Second, the lookup doesn't guarantee that only one object will be returned.
  137. If the query matches more than one object, it will retrieve and transfer all of
  138. them from the database. This penalty could be substantial if hundreds or
  139. thousands of records are returned. The penalty will be compounded if the
  140. database lives on a separate server, where network overhead and latency also
  141. play a factor.
  142. Retrieve everything at once if you know you will need it
  143. ========================================================
  144. Hitting the database multiple times for different parts of a single 'set' of
  145. data that you will need all parts of is, in general, less efficient than
  146. retrieving it all in one query. This is particularly important if you have a
  147. query that is executed in a loop, and could therefore end up doing many database
  148. queries, when only one was needed. So:
  149. Use ``QuerySet.select_related()`` and ``prefetch_related()``
  150. ------------------------------------------------------------
  151. Understand :meth:`~django.db.models.query.QuerySet.select_related` and
  152. :meth:`~django.db.models.query.QuerySet.prefetch_related` thoroughly, and use
  153. them:
  154. * in :doc:`managers and default managers </topics/db/managers>` where
  155. appropriate. Be aware when your manager is and is not used; sometimes this is
  156. tricky so don't make assumptions.
  157. * in view code or other layers, possibly making use of
  158. :func:`~django.db.models.prefetch_related_objects` where needed.
  159. Don't retrieve things you don't need
  160. ====================================
  161. Use ``QuerySet.values()`` and ``values_list()``
  162. -----------------------------------------------
  163. When you only want a ``dict`` or ``list`` of values, and don't need ORM model
  164. objects, make appropriate usage of
  165. :meth:`~django.db.models.query.QuerySet.values()`.
  166. These can be useful for replacing model objects in template code - as long as
  167. the dicts you supply have the same attributes as those used in the template,
  168. you are fine.
  169. Use ``QuerySet.defer()`` and ``only()``
  170. ---------------------------------------
  171. Use :meth:`~django.db.models.query.QuerySet.defer()` and
  172. :meth:`~django.db.models.query.QuerySet.only()` if there are database columns
  173. you know that you won't need (or won't need in most cases) to avoid loading
  174. them. Note that if you *do* use them, the ORM will have to go and get them in
  175. a separate query, making this a pessimization if you use it inappropriately.
  176. Don't be too aggressive in deferring fields without profiling as the database
  177. has to read most of the non-text, non-``VARCHAR`` data from the disk for a
  178. single row in the results, even if it ends up only using a few columns. The
  179. ``defer()`` and ``only()`` methods are most useful when you can avoid loading a
  180. lot of text data or for fields that might take a lot of processing to convert
  181. back to Python. As always, profile first, then optimize.
  182. Use ``QuerySet.contains(obj)``
  183. ------------------------------
  184. ...if you only want to find out if ``obj`` is in the queryset, rather than
  185. ``if obj in queryset``.
  186. Use ``QuerySet.count()``
  187. ------------------------
  188. ...if you only want the count, rather than doing ``len(queryset)``.
  189. Use ``QuerySet.exists()``
  190. -------------------------
  191. ...if you only want to find out if at least one result exists, rather than ``if
  192. queryset``.
  193. But:
  194. .. _overuse_of_count_and_exists:
  195. Don't overuse ``contains()``, ``count()``, and ``exists()``
  196. -----------------------------------------------------------
  197. If you are going to need other data from the QuerySet, evaluate it immediately.
  198. For example, assuming a ``Group`` model that has a many-to-many relation to
  199. ``User``, the following code is optimal::
  200. members = group.members.all()
  201. if display_group_members:
  202. if members:
  203. if current_user in members:
  204. print("You and", len(members) - 1, "other users are members of this group.")
  205. else:
  206. print("There are", len(members), "members in this group.")
  207. for member in members:
  208. print(member.username)
  209. else:
  210. print("There are no members in this group.")
  211. It is optimal because:
  212. #. Since QuerySets are lazy, this does no database queries if
  213. ``display_group_members`` is ``False``.
  214. #. Storing ``group.members.all()`` in the ``members`` variable allows its
  215. result cache to be reused.
  216. #. The line ``if members:`` causes ``QuerySet.__bool__()`` to be called, which
  217. causes the ``group.members.all()`` query to be run on the database. If there
  218. aren't any results, it will return ``False``, otherwise ``True``.
  219. #. The line ``if current_user in members:`` checks if the user is in the result
  220. cache, so no additional database queries are issued.
  221. #. The use of ``len(members)`` calls ``QuerySet.__len__()``, reusing the result
  222. cache, so again, no database queries are issued.
  223. #. The ``for member`` loop iterates over the result cache.
  224. In total, this code does either one or zero database queries. The only
  225. deliberate optimization performed is using the ``members`` variable. Using
  226. ``QuerySet.exists()`` for the ``if``, ``QuerySet.contains()`` for the ``in``,
  227. or ``QuerySet.count()`` for the count would each cause additional queries.
  228. Use ``QuerySet.update()`` and ``delete()``
  229. ------------------------------------------
  230. Rather than retrieve a load of objects, set some values, and save them
  231. individual, use a bulk SQL UPDATE statement, via :ref:`QuerySet.update()
  232. <topics-db-queries-update>`. Similarly, do :ref:`bulk deletes
  233. <topics-db-queries-delete>` where possible.
  234. Note, however, that these bulk update methods cannot call the ``save()`` or
  235. ``delete()`` methods of individual instances, which means that any custom
  236. behavior you have added for these methods will not be executed, including
  237. anything driven from the normal database object :doc:`signals </ref/signals>`.
  238. Use foreign key values directly
  239. -------------------------------
  240. If you only need a foreign key value, use the foreign key value that is already on
  241. the object you've got, rather than getting the whole related object and taking
  242. its primary key. i.e. do::
  243. entry.blog_id
  244. instead of::
  245. entry.blog.id
  246. Don't order results if you don't care
  247. -------------------------------------
  248. Ordering is not free; each field to order by is an operation the database must
  249. perform. If a model has a default ordering (:attr:`Meta.ordering
  250. <django.db.models.Options.ordering>`) and you don't need it, remove
  251. it on a ``QuerySet`` by calling
  252. :meth:`~django.db.models.query.QuerySet.order_by()` with no parameters.
  253. Adding an index to your database may help to improve ordering performance.
  254. Use bulk methods
  255. ================
  256. Use bulk methods to reduce the number of SQL statements.
  257. Create in bulk
  258. --------------
  259. When creating objects, where possible, use the
  260. :meth:`~django.db.models.query.QuerySet.bulk_create()` method to reduce the
  261. number of SQL queries. For example::
  262. Entry.objects.bulk_create(
  263. [
  264. Entry(headline="This is a test"),
  265. Entry(headline="This is only a test"),
  266. ]
  267. )
  268. ...is preferable to::
  269. Entry.objects.create(headline="This is a test")
  270. Entry.objects.create(headline="This is only a test")
  271. Note that there are a number of :meth:`caveats to this method
  272. <django.db.models.query.QuerySet.bulk_create>`, so make sure it's appropriate
  273. for your use case.
  274. Update in bulk
  275. --------------
  276. When updating objects, where possible, use the
  277. :meth:`~django.db.models.query.QuerySet.bulk_update()` method to reduce the
  278. number of SQL queries. Given a list or queryset of objects::
  279. entries = Entry.objects.bulk_create(
  280. [
  281. Entry(headline="This is a test"),
  282. Entry(headline="This is only a test"),
  283. ]
  284. )
  285. The following example::
  286. entries[0].headline = "This is not a test"
  287. entries[1].headline = "This is no longer a test"
  288. Entry.objects.bulk_update(entries, ["headline"])
  289. ...is preferable to::
  290. entries[0].headline = "This is not a test"
  291. entries[0].save()
  292. entries[1].headline = "This is no longer a test"
  293. entries[1].save()
  294. Note that there are a number of :meth:`caveats to this method
  295. <django.db.models.query.QuerySet.bulk_update>`, so make sure it's appropriate
  296. for your use case.
  297. Insert in bulk
  298. --------------
  299. When inserting objects into :class:`ManyToManyFields
  300. <django.db.models.ManyToManyField>`, use
  301. :meth:`~django.db.models.fields.related.RelatedManager.add` with multiple
  302. objects to reduce the number of SQL queries. For example::
  303. my_band.members.add(me, my_friend)
  304. ...is preferable to::
  305. my_band.members.add(me)
  306. my_band.members.add(my_friend)
  307. ...where ``Bands`` and ``Artists`` have a many-to-many relationship.
  308. When inserting different pairs of objects into
  309. :class:`~django.db.models.ManyToManyField` or when the custom
  310. :attr:`~django.db.models.ManyToManyField.through` table is defined, use
  311. :meth:`~django.db.models.query.QuerySet.bulk_create()` method to reduce the
  312. number of SQL queries. For example::
  313. PizzaToppingRelationship = Pizza.toppings.through
  314. PizzaToppingRelationship.objects.bulk_create(
  315. [
  316. PizzaToppingRelationship(pizza=my_pizza, topping=pepperoni),
  317. PizzaToppingRelationship(pizza=your_pizza, topping=pepperoni),
  318. PizzaToppingRelationship(pizza=your_pizza, topping=mushroom),
  319. ],
  320. ignore_conflicts=True,
  321. )
  322. ...is preferable to::
  323. my_pizza.toppings.add(pepperoni)
  324. your_pizza.toppings.add(pepperoni, mushroom)
  325. ...where ``Pizza`` and ``Topping`` have a many-to-many relationship. Note that
  326. there are a number of :meth:`caveats to this method
  327. <django.db.models.query.QuerySet.bulk_create>`, so make sure it's appropriate
  328. for your use case.
  329. Remove in bulk
  330. --------------
  331. When removing objects from :class:`ManyToManyFields
  332. <django.db.models.ManyToManyField>`, use
  333. :meth:`~django.db.models.fields.related.RelatedManager.remove` with multiple
  334. objects to reduce the number of SQL queries. For example::
  335. my_band.members.remove(me, my_friend)
  336. ...is preferable to::
  337. my_band.members.remove(me)
  338. my_band.members.remove(my_friend)
  339. ...where ``Bands`` and ``Artists`` have a many-to-many relationship.
  340. When removing different pairs of objects from :class:`ManyToManyFields
  341. <django.db.models.ManyToManyField>`, use
  342. :meth:`~django.db.models.query.QuerySet.delete` on a
  343. :class:`~django.db.models.Q` expression with multiple
  344. :attr:`~django.db.models.ManyToManyField.through` model instances to reduce
  345. the number of SQL queries. For example::
  346. from django.db.models import Q
  347. PizzaToppingRelationship = Pizza.toppings.through
  348. PizzaToppingRelationship.objects.filter(
  349. Q(pizza=my_pizza, topping=pepperoni)
  350. | Q(pizza=your_pizza, topping=pepperoni)
  351. | Q(pizza=your_pizza, topping=mushroom)
  352. ).delete()
  353. ...is preferable to::
  354. my_pizza.toppings.remove(pepperoni)
  355. your_pizza.toppings.remove(pepperoni, mushroom)
  356. ...where ``Pizza`` and ``Topping`` have a many-to-many relationship.