lookups.txt 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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. The two prominent examples are
  27. :class:`~django.db.models.Field`, the base class of all model fields, and
  28. ``Aggregate``, the base class of all Django aggregates.
  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. For example
  33. ``DateField.register_lookup(YearExact)`` will register ``YearExact``
  34. lookup on ``DateField``. It overrides a lookup that already exists with
  35. the same name. ``lookup_name`` will be used for this lookup if
  36. provided, otherwise ``lookup.lookup_name`` will be used.
  37. .. method:: get_lookup(lookup_name)
  38. Returns the :class:`Lookup` named ``lookup_name`` registered in the class.
  39. The default implementation looks recursively on all parent classes
  40. and checks if any has a registered lookup named ``lookup_name``, returning
  41. the first match.
  42. .. method:: get_lookups()
  43. Returns a dictionary of each lookup name registered in the class mapped
  44. to the :class:`Lookup` class.
  45. .. method:: get_transform(transform_name)
  46. Returns a :class:`Transform` named ``transform_name``. The default
  47. implementation looks recursively on all parent classes to check if any
  48. has the registered transform named ``transform_name``, returning the first
  49. match.
  50. For a class to be a lookup, it must follow the :ref:`Query Expression API
  51. <query-expression>`. :class:`~Lookup` and :class:`~Transform` naturally
  52. follow this API.
  53. .. _query-expression:
  54. The Query Expression API
  55. ========================
  56. The query expression API is a common set of methods that classes define to be
  57. usable in query expressions to translate themselves into SQL expressions. Direct
  58. field references, aggregates, and ``Transform`` are examples that follow this
  59. API. A class is said to follow the query expression API when it implements the
  60. following methods:
  61. .. method:: as_sql(compiler, connection)
  62. Responsible for producing the query string and parameters for the expression.
  63. The ``compiler`` is an ``SQLCompiler`` object, which has a ``compile()``
  64. method that can be used to compile other expressions. The ``connection`` is
  65. the connection used to execute the query.
  66. Calling ``expression.as_sql()`` is usually incorrect - instead
  67. ``compiler.compile(expression)`` should be used. The ``compiler.compile()``
  68. method will take care of calling vendor-specific methods of the expression.
  69. Custom keyword arguments may be defined on this method if it's likely that
  70. ``as_vendorname()`` methods or subclasses will need to supply data to
  71. override the generation of the SQL string. See :meth:`Func.as_sql` for
  72. example usage.
  73. .. method:: as_vendorname(compiler, connection)
  74. Works like ``as_sql()`` method. When an expression is compiled by
  75. ``compiler.compile()``, Django will first try to call ``as_vendorname()``,
  76. where ``vendorname`` is the vendor name of the backend used for executing
  77. the query. The ``vendorname`` is one of ``postgresql``, ``oracle``,
  78. ``sqlite``, or ``mysql`` for Django's built-in backends.
  79. .. method:: get_lookup(lookup_name)
  80. Must return the lookup named ``lookup_name``. For instance, by returning
  81. ``self.output_field.get_lookup(lookup_name)``.
  82. .. method:: get_transform(transform_name)
  83. Must return the lookup named ``transform_name``. For instance, by returning
  84. ``self.output_field.get_transform(transform_name)``.
  85. .. attribute:: output_field
  86. Defines the type of class returned by the ``get_lookup()`` method. It must
  87. be a :class:`~django.db.models.Field` instance.
  88. ``Transform`` reference
  89. =======================
  90. .. class:: Transform
  91. A ``Transform`` is a generic class to implement field transformations. A
  92. prominent example is ``__year`` that transforms a ``DateField`` into a
  93. ``IntegerField``.
  94. The notation to use a ``Transform`` in an lookup expression is
  95. ``<expression>__<transformation>`` (e.g. ``date__year``).
  96. This class follows the :ref:`Query Expression API <query-expression>`, which
  97. implies that you can use ``<expression>__<transform1>__<transform2>``. It's
  98. a specialized :ref:`Func() expression <func-expressions>` that only accepts
  99. one argument. It can also be used on the right hand side of a filter or
  100. directly as an annotation.
  101. .. attribute:: bilateral
  102. A boolean indicating whether this transformation should apply to both
  103. ``lhs`` and ``rhs``. Bilateral transformations will be applied to ``rhs`` in
  104. the same order as they appear in the lookup expression. By default it is set
  105. to ``False``. For example usage, see :doc:`/howto/custom-lookups`.
  106. .. attribute:: lhs
  107. The left-hand side - what is being transformed. It must follow the
  108. :ref:`Query Expression API <query-expression>`.
  109. .. attribute:: lookup_name
  110. The name of the lookup, used for identifying it on parsing query
  111. expressions. It cannot contain the string ``"__"``.
  112. .. attribute:: output_field
  113. Defines the class this transformation outputs. It must be a
  114. :class:`~django.db.models.Field` instance. By default is the same as
  115. its ``lhs.output_field``.
  116. ``Lookup`` reference
  117. ====================
  118. .. class:: Lookup
  119. A ``Lookup`` is a generic class to implement lookups. A lookup is a query
  120. expression with a left-hand side, :attr:`lhs`; a right-hand side,
  121. :attr:`rhs`; and a ``lookup_name`` that is used to produce a boolean
  122. comparison between ``lhs`` and ``rhs`` such as ``lhs in rhs`` or
  123. ``lhs > rhs``.
  124. The notation to use a lookup in an expression is
  125. ``<lhs>__<lookup_name>=<rhs>``.
  126. This class doesn't follow the :ref:`Query Expression API <query-expression>`
  127. since it has ``=<rhs>`` on its construction: lookups are always the end of
  128. a lookup expression.
  129. .. attribute:: lhs
  130. The left-hand side - what is being looked up. The object must follow
  131. the :ref:`Query Expression API <query-expression>`.
  132. .. attribute:: rhs
  133. The right-hand side - what ``lhs`` is being compared against. It can be
  134. a plain value, or something that compiles into SQL, typically an
  135. ``F()`` object or a ``QuerySet``.
  136. .. attribute:: lookup_name
  137. The name of this lookup, used to identify it on parsing query
  138. expressions. It cannot contain the string ``"__"``.
  139. .. method:: process_lhs(compiler, connection, lhs=None)
  140. Returns a tuple ``(lhs_string, lhs_params)``, as returned by
  141. ``compiler.compile(lhs)``. This method can be overridden to tune how
  142. the ``lhs`` is processed.
  143. ``compiler`` is an ``SQLCompiler`` object, to be used like
  144. ``compiler.compile(lhs)`` for compiling ``lhs``. The ``connection``
  145. can be used for compiling vendor specific SQL. If ``lhs`` is not
  146. ``None``, use it as the processed ``lhs`` instead of ``self.lhs``.
  147. .. method:: process_rhs(compiler, connection)
  148. Behaves the same way as :meth:`process_lhs`, for the right-hand side.