queries.txt 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. =====================
  2. Query-related classes
  3. =====================
  4. .. currentmodule:: django.db.models
  5. This document provides reference material for query-related tools not
  6. documented elsewhere.
  7. ``F()`` expressions
  8. ===================
  9. .. class:: F
  10. An ``F()`` object represents the value of a model field. It makes it possible
  11. to refer to model field values and perform database operations using them
  12. without actually having to pull them out of the database into Python memory.
  13. Instead, Django uses the ``F()`` object to generate a SQL expression that
  14. describes the required operation at the database level.
  15. This is easiest to understand though an example. Normally, one might do
  16. something like this::
  17. # Tintin filed a news story!
  18. reporter = Reporters.objects.get(name='Tintin')
  19. reporter.stories_filed += 1
  20. reporter.save()
  21. Here, we have pulled the value of ``reporter.stories_filed`` from the database
  22. into memory and manipulated it using familiar Python operators, and then saved
  23. the object back to the database. But instead we could also have done::
  24. from django.db.models import F
  25. reporter = Reporters.objects.get(name='Tintin')
  26. reporter.stories_filed = F('stories_filed') + 1
  27. reporter.save()
  28. Although ``reporter.stories_filed = F('stories_filed') + 1`` looks like a
  29. normal Python assignment of value to an instance attribute, in fact it's an SQL
  30. construct describing an operation on the database.
  31. When Django encounters an instance of ``F()``, it overrides the standard Python
  32. operators to create an encapsulated SQL expression; in this case, one which
  33. instructs the database to increment the database field represented by
  34. ``reporter.stories_filed``.
  35. Whatever value is or was on ``reporter.stories_filed``, Python never gets to
  36. know about it - it is dealt with entirely by the database. All Python does,
  37. through Django's ``F()`` class, is create the SQL syntax to refer to the field
  38. and describe the operation.
  39. .. note::
  40. In order to access the new value that has been saved in this way, the object
  41. will need to be reloaded::
  42. reporter = Reporters.objects.get(pk=reporter.pk)
  43. As well as being used in operations on single instances as above, ``F()`` can
  44. be used on ``QuerySets`` of object instances, with ``update()``. This reduces
  45. the two queries we were using above - the ``get()`` and the
  46. :meth:`~Model.save()` - to just one::
  47. reporter = Reporters.objects.filter(name='Tintin')
  48. reporter.update(stories_filed=F('stories_filed') + 1)
  49. We can also use :meth:`~django.db.models.query.QuerySet.update()` to increment
  50. the field value on multiple objects - which could be very much faster than
  51. pulling them all into Python from the database, looping over them, incrementing
  52. the field value of each one, and saving each one back to the database::
  53. Reporter.objects.all().update(stories_filed=F('stories_filed) + 1)
  54. ``F()`` therefore can offer performance advantages by:
  55. * getting the database, rather than Python, to do work
  56. * reducing the number of queries some operations require
  57. .. _avoiding-race-conditions-using-f:
  58. Avoiding race conditions using ``F()``
  59. --------------------------------------
  60. Another useful benefit of ``F()`` is that having the database - rather than
  61. Python - update a field's value avoids a *race condition*.
  62. If two Python threads execute the code in the first example above, one thread
  63. could retrieve, increment, and save a field's value after the other has
  64. retrieved it from the database. The value that the second thread saves will be
  65. based on the original value; the work of the first thread will simply be lost.
  66. If the database is responsible for updating the field, the process is more
  67. robust: it will only ever update the field based on the value of the field in
  68. the database when the :meth:`~Model.save()` or ``update()`` is executed, rather
  69. than based on its value when the instance was retrieved.
  70. Using ``F()`` in filters
  71. ------------------------
  72. ``F()`` is also very useful in ``QuerySet`` filters, where they make it
  73. possible to filter a set of objects against criteria based on their field
  74. values, rather than on Python values.
  75. This is documented in :ref:`using F() expressions in queries
  76. <using-f-expressions-in-filters>`
  77. Supported operations with ``F()``
  78. ---------------------------------
  79. As well as addition, Django supports subtraction, multiplication, division,
  80. and modulo arithmetic with ``F()`` objects, using Python constants,
  81. variables, and even other ``F()`` objects.
  82. ``Q()`` objects
  83. ===============
  84. .. class:: Q
  85. A ``Q()`` object, like an :class:`~django.db.models.F` object, encapsulates a
  86. SQL expression in a Python object that can be used in database-related
  87. operations.
  88. In general, ``Q() objects`` make it possible to define and reuse conditions.
  89. This permits the :ref:`construction of complex database queries
  90. <complex-lookups-with-q>` using ``|`` (``OR``) and ``&`` (``AND``) operators;
  91. in particular, it is not otherwise possible to use ``OR`` in ``QuerySets``.