lookups.txt 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. ====================
  2. Lookup API reference
  3. ====================
  4. .. module:: django.db.models.lookups
  5. :synopsis: Lookups API
  6. .. currentmodule:: django.db.models
  7. .. versionadded:: 1.7
  8. This document has the API references of lookups, the Django API for building
  9. the ``WHERE`` clause of a database query. To learn how to *use* lookups, see
  10. :doc:`/topics/db/queries`; to learn how to *create* new lookups, see
  11. :doc:`/howto/custom-lookups`.
  12. The lookup API has two components: a :class:`~lookups.RegisterLookupMixin` class
  13. that registers lookups, and the `Query Expression API <query-expression>`_, a
  14. set of methods that a class has to implement to be registrable as a lookup.
  15. Django has two base classes that follow the query expression API and from where
  16. all Django builtin lookups are derived:
  17. * :class:`Lookup`: to lookup a field (e.g. the ``exact`` of ``field_name__exact``)
  18. * :class:`Transform`: to transform a field
  19. A lookup expression consists of three parts:
  20. * Fields part (e.g. ``Book.objects.filter(author__best_friends__first_name...``);
  21. * Transforms part (may be omitted) (e.g. ``__lower__first3chars__reversed``);
  22. * A lookup (e.g. ``__icontains``) that, if omitted, defaults to ``__exact``.
  23. .. _lookup-registration-api:
  24. Registration API
  25. ~~~~~~~~~~~~~~~~
  26. Django uses :class:`~lookups.RegisterLookupMixin` to give a class the interface to
  27. register lookups on itself. The two prominent examples are
  28. :class:`~django.db.models.Field`, the base class of all model fields, and
  29. ``Aggregate``, the base class of all Django aggregates.
  30. .. class:: lookups.RegisterLookupMixin
  31. A mixin that implements the lookup API on a class.
  32. .. classmethod:: register_lookup(lookup)
  33. Registers a new lookup in the class. For example
  34. ``DateField.register_lookup(YearExact)`` will register ``YearExact``
  35. lookup on ``DateField``. It overrides a lookup that already exists with
  36. the same name.
  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_transform(transform_name)
  43. Returns a :class:`Transform` named ``transform_name``. The default
  44. implementation looks recursively on all parent classes to check if any
  45. has the registered transform named ``transform_name``, returning the first
  46. match.
  47. For a class to be a lookup, it must follow the `Query Expression API
  48. <query-expression>`_. :class:`~Lookup` and :class:`~Transform` naturally
  49. follow this API.
  50. .. _query-expression:
  51. The Query Expression API
  52. ~~~~~~~~~~~~~~~~~~~~~~~~
  53. The query expression API is a common set of methods that classes define to be
  54. usable in query expressions to translate themselves into SQL expressions. Direct
  55. field references, aggregates, and ``Transform`` are examples that follow this
  56. API. A class is said to follow the query expression API when it implements the
  57. following methods:
  58. .. method:: as_sql(self, qn, connection)
  59. Responsible for producing the query string and parameters for the expression.
  60. The ``qn`` is an ``SQLCompiler`` object, which has a ``compile()`` method
  61. that can be used to compile other expressions. The ``connection`` is the
  62. connection used to execute the query.
  63. Calling ``expression.as_sql()`` is usually incorrect - instead
  64. ``qn.compile(expression)`` should be used. The ``qn.compile()`` method will
  65. take care of calling vendor-specific methods of the expression.
  66. .. method:: as_vendorname(self, qn, connection)
  67. Works like ``as_sql()`` method. When an expression is compiled by
  68. ``qn.compile()``, Django will first try to call ``as_vendorname()``, where
  69. ``vendorname`` is the vendor name of the backend used for executing the
  70. query. The ``vendorname`` is one of ``postgresql``, ``oracle``, ``sqlite``,
  71. or ``mysql`` for Django's built-in backends.
  72. .. method:: get_lookup(lookup_name)
  73. Must return the lookup named ``lookup_name``. For instance, by returning
  74. ``self.output_field.get_lookup(lookup_name)``.
  75. .. method:: get_transform(transform_name)
  76. Must return the lookup named ``transform_name``. For instance, by returning
  77. ``self.output_field.get_transform(transform_name)``.
  78. .. attribute:: output_field
  79. Defines the type of class returned by the ``get_lookup()`` method. It must
  80. be a :class:`~django.db.models.Field` instance.
  81. Transform reference
  82. ~~~~~~~~~~~~~~~~~~~
  83. .. class:: Transform
  84. A ``Transform`` is a generic class to implement field transformations. A
  85. prominent example is ``__year`` that transforms a ``DateField`` into a
  86. ``IntegerField``.
  87. The notation to use a ``Transform`` in an lookup expression is
  88. ``<expression>__<transformation>`` (e.g. ``date__year``).
  89. This class follows the `Query Expression API <query-expression>`_, which
  90. implies that you can use ``<expression>__<transform1>__<transform2>``.
  91. .. attribute:: lhs
  92. The left-hand side - what is being transformed. It must follow the
  93. `Query Expression API <query-expression>`_.
  94. .. attribute:: lookup_name
  95. The name of the lookup, used for identifying it on parsing query
  96. expressions. It cannot contain the string ``"__"``.
  97. .. attribute:: output_field
  98. Defines the class this transformation outputs. It must be a
  99. :class:`~django.db.models.Field` instance. By default is the same as
  100. its ``lhs.output_field``.
  101. .. method:: as_sql
  102. To be overridden; raises :exc:`NotImplementedError`.
  103. .. method:: get_lookup(lookup_name)
  104. Same as :meth:`~lookups.RegisterLookupMixin.get_lookup()`.
  105. .. method:: get_transform(transform_name)
  106. Same as :meth:`~lookups.RegisterLookupMixin.get_transform()`.
  107. Lookup reference
  108. ~~~~~~~~~~~~~~~~
  109. .. class:: Lookup
  110. A ``Lookup`` is a generic class to implement lookups. A lookup is a query
  111. expression with a left-hand side, :attr:`lhs`; a right-hand side,
  112. :attr:`rhs`; and a ``lookup_name`` that is used to produce a boolean
  113. comparison between ``lhs`` and ``rhs`` such as ``lhs in rhs`` or
  114. ``lhs > rhs``.
  115. The notation to use a lookup in an expression is
  116. ``<lhs>__<lookup_name>=<rhs>``.
  117. This class doesn't follow the `Query Expression API <query-expression>`_
  118. since it has ``=<rhs>`` on its construction: lookups are always the end of
  119. a lookup expression.
  120. .. attribute:: lhs
  121. The left-hand side - what is being looked up. The object must follow
  122. the `Query Expression API <query-expression>`_.
  123. .. attribute:: rhs
  124. The right-hand side - what ``lhs`` is being compared against. It can be
  125. a plain value, or something that compiles into SQL, typically an
  126. ``F()`` object or a ``QuerySet``.
  127. .. attribute:: lookup_name
  128. The name of this lookup, used to identify it on parsing query
  129. expressions. It cannot contain the string ``"__"``.
  130. .. method:: process_lhs(qn, connection[, lhs=None])
  131. Returns a tuple ``(lhs_string, lhs_params)``, as returned by
  132. ``qn.compile(lhs)``. This method can be overridden to tune how the
  133. ``lhs`` is processed.
  134. ``qn`` is an ``SQLCompiler`` object, to be used like ``qn.compile(lhs)``
  135. for compiling ``lhs``. The ``connection`` can be used for compiling
  136. vendor specific SQL. If ``lhs`` is not ``None``, use it as the
  137. processed ``lhs`` instead of ``self.lhs``.
  138. .. method:: process_rhs(qn, connection)
  139. Behaves the same way as :meth:`process_lhs`, for the right-hand side.