lookups.txt 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. ====================
  2. Lookup API reference
  3. ====================
  4. .. module:: django.db.models.lookups
  5. :synopsis: Lookups API
  6. .. currentmodule:: django.db.models
  7. This document has the API references of lookups, the Django API for building
  8. the ``WHERE`` clause of a database query. To learn how to *use* lookups, see
  9. :doc:`/topics/db/queries`; to learn how to *create* new lookups, see
  10. :doc:`/howto/custom-lookups`.
  11. The lookup API has two components: a :class:`~lookups.RegisterLookupMixin` class
  12. that registers lookups, and the :ref:`Query Expression API <query-expression>`, a
  13. set of methods that a class has to implement to be registrable as a lookup.
  14. Django has two base classes that follow the query expression API and from where
  15. all Django builtin lookups are derived:
  16. * :class:`Lookup`: to lookup a field (e.g. the ``exact`` of ``field_name__exact``)
  17. * :class:`Transform`: to transform a field
  18. A lookup expression consists of three parts:
  19. * Fields part (e.g. ``Book.objects.filter(author__best_friends__first_name...``);
  20. * Transforms part (may be omitted) (e.g. ``__lower__first3chars__reversed``);
  21. * A lookup (e.g. ``__icontains``) that, if omitted, defaults to ``__exact``.
  22. .. _lookup-registration-api:
  23. Registration API
  24. ================
  25. Django uses :class:`~lookups.RegisterLookupMixin` to give a class the interface to
  26. register lookups on itself or its instances. The two prominent examples are
  27. :class:`~django.db.models.Field`, the base class of all model fields, and
  28. :class:`Transform`, the base class of all Django transforms.
  29. .. class:: lookups.RegisterLookupMixin
  30. A mixin that implements the lookup API on a class.
  31. .. classmethod:: register_lookup(lookup, lookup_name=None)
  32. Registers a new lookup in the class or class instance. For example::
  33. DateField.register_lookup(YearExact)
  34. User._meta.get_field("date_joined").register_lookup(MonthExact)
  35. will register ``YearExact`` lookup on ``DateField`` and ``MonthExact``
  36. lookup on the ``User.date_joined`` (you can use :ref:`Field Access API
  37. <model-meta-field-api>` to retrieve a single field instance). It
  38. overrides a lookup that already exists with the same name. Lookups
  39. registered on field instances take precedence over the lookups
  40. registered on classes. ``lookup_name`` will be used for this lookup if
  41. provided, otherwise ``lookup.lookup_name`` will be used.
  42. .. method:: get_lookup(lookup_name)
  43. Returns the :class:`Lookup` named ``lookup_name`` registered in the
  44. class or class instance depending on what calls it. The default
  45. implementation looks recursively on all parent classes and checks if
  46. any has a registered lookup named ``lookup_name``, returning the first
  47. match. Instance lookups would override any class lookups with the same
  48. ``lookup_name``.
  49. .. method:: get_lookups()
  50. Returns a dictionary of each lookup name registered in the class or
  51. class instance mapped to the :class:`Lookup` class.
  52. .. method:: get_transform(transform_name)
  53. Returns a :class:`Transform` named ``transform_name`` registered in the
  54. class or class instance. The default implementation looks recursively
  55. on all parent classes to check if any has the registered transform
  56. named ``transform_name``, returning the first match.
  57. For a class to be a lookup, it must follow the :ref:`Query Expression API
  58. <query-expression>`. :class:`~Lookup` and :class:`~Transform` naturally
  59. follow this API.
  60. .. versionchanged:: 4.2
  61. Support for registering lookups on :class:`~django.db.models.Field`
  62. instances was added.
  63. .. _query-expression:
  64. The Query Expression API
  65. ========================
  66. The query expression API is a common set of methods that classes define to be
  67. usable in query expressions to translate themselves into SQL expressions. Direct
  68. field references, aggregates, and ``Transform`` are examples that follow this
  69. API. A class is said to follow the query expression API when it implements the
  70. following methods:
  71. .. method:: as_sql(compiler, connection)
  72. Generates the SQL fragment for the expression. Returns a tuple
  73. ``(sql, params)``, where ``sql`` is the SQL string, and ``params`` is the
  74. list or tuple of query parameters. The ``compiler`` is an ``SQLCompiler``
  75. object, which has a ``compile()`` method that can be used to compile other
  76. expressions. The ``connection`` is the connection used to execute the
  77. query.
  78. Calling ``expression.as_sql()`` is usually incorrect - instead
  79. ``compiler.compile(expression)`` should be used. The ``compiler.compile()``
  80. method will take care of calling vendor-specific methods of the expression.
  81. Custom keyword arguments may be defined on this method if it's likely that
  82. ``as_vendorname()`` methods or subclasses will need to supply data to
  83. override the generation of the SQL string. See :meth:`Func.as_sql` for
  84. example usage.
  85. .. method:: as_vendorname(compiler, connection)
  86. Works like ``as_sql()`` method. When an expression is compiled by
  87. ``compiler.compile()``, Django will first try to call ``as_vendorname()``,
  88. where ``vendorname`` is the vendor name of the backend used for executing
  89. the query. The ``vendorname`` is one of ``postgresql``, ``oracle``,
  90. ``sqlite``, or ``mysql`` for Django's built-in backends.
  91. .. method:: get_lookup(lookup_name)
  92. Must return the lookup named ``lookup_name``. For instance, by returning
  93. ``self.output_field.get_lookup(lookup_name)``.
  94. .. method:: get_transform(transform_name)
  95. Must return the lookup named ``transform_name``. For instance, by returning
  96. ``self.output_field.get_transform(transform_name)``.
  97. .. attribute:: output_field
  98. Defines the type of class returned by the ``get_lookup()`` method. It must
  99. be a :class:`~django.db.models.Field` instance.
  100. ``Transform`` reference
  101. =======================
  102. .. class:: Transform
  103. A ``Transform`` is a generic class to implement field transformations. A
  104. prominent example is ``__year`` that transforms a ``DateField`` into a
  105. ``IntegerField``.
  106. The notation to use a ``Transform`` in a lookup expression is
  107. ``<expression>__<transformation>`` (e.g. ``date__year``).
  108. This class follows the :ref:`Query Expression API <query-expression>`, which
  109. implies that you can use ``<expression>__<transform1>__<transform2>``. It's
  110. a specialized :ref:`Func() expression <func-expressions>` that only accepts
  111. one argument. It can also be used on the right hand side of a filter or
  112. directly as an annotation.
  113. .. attribute:: bilateral
  114. A boolean indicating whether this transformation should apply to both
  115. ``lhs`` and ``rhs``. Bilateral transformations will be applied to ``rhs`` in
  116. the same order as they appear in the lookup expression. By default it is set
  117. to ``False``. For example usage, see :doc:`/howto/custom-lookups`.
  118. .. attribute:: lhs
  119. The left-hand side - what is being transformed. It must follow the
  120. :ref:`Query Expression API <query-expression>`.
  121. .. attribute:: lookup_name
  122. The name of the lookup, used for identifying it on parsing query
  123. expressions. It cannot contain the string ``"__"``.
  124. .. attribute:: output_field
  125. Defines the class this transformation outputs. It must be a
  126. :class:`~django.db.models.Field` instance. By default is the same as
  127. its ``lhs.output_field``.
  128. ``Lookup`` reference
  129. ====================
  130. .. class:: Lookup
  131. A ``Lookup`` is a generic class to implement lookups. A lookup is a query
  132. expression with a left-hand side, :attr:`lhs`; a right-hand side,
  133. :attr:`rhs`; and a ``lookup_name`` that is used to produce a boolean
  134. comparison between ``lhs`` and ``rhs`` such as ``lhs in rhs`` or
  135. ``lhs > rhs``.
  136. The primary notation to use a lookup in an expression is
  137. ``<lhs>__<lookup_name>=<rhs>``. Lookups can also be used directly in
  138. ``QuerySet`` filters::
  139. Book.objects.filter(LessThan(F("word_count"), 7500))
  140. …or annotations::
  141. Book.objects.annotate(is_short_story=LessThan(F("word_count"), 7500))
  142. .. attribute:: lhs
  143. The left-hand side - what is being looked up. The object typically
  144. follows the :ref:`Query Expression API <query-expression>`. It may also
  145. be a plain value.
  146. .. attribute:: rhs
  147. The right-hand side - what ``lhs`` is being compared against. It can be
  148. a plain value, or something that compiles into SQL, typically an
  149. ``F()`` object or a ``QuerySet``.
  150. .. attribute:: lookup_name
  151. The name of this lookup, used to identify it on parsing query
  152. expressions. It cannot contain the string ``"__"``.
  153. .. attribute:: prepare_rhs
  154. Defaults to ``True``. When :attr:`rhs` is a plain value,
  155. :attr:`prepare_rhs` determines whether it should be prepared for use as
  156. a parameter in a query. In order to do so,
  157. ``lhs.output_field.get_prep_value()`` is called if defined, or ``rhs``
  158. is wrapped in :class:`Value() <django.db.models.Value>` otherwise.
  159. .. method:: process_lhs(compiler, connection, lhs=None)
  160. Returns a tuple ``(lhs_string, lhs_params)``, as returned by
  161. ``compiler.compile(lhs)``. This method can be overridden to tune how
  162. the ``lhs`` is processed.
  163. ``compiler`` is an ``SQLCompiler`` object, to be used like
  164. ``compiler.compile(lhs)`` for compiling ``lhs``. The ``connection``
  165. can be used for compiling vendor specific SQL. If ``lhs`` is not
  166. ``None``, use it as the processed ``lhs`` instead of ``self.lhs``.
  167. .. method:: process_rhs(compiler, connection)
  168. Behaves the same way as :meth:`process_lhs`, for the right-hand side.