database-functions.txt 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. ==================
  2. Database Functions
  3. ==================
  4. .. module:: django.db.models.functions
  5. :synopsis: Database Functions
  6. The classes documented below provide a way for users to use functions provided
  7. by the underlying database as annotations, aggregations, or filters in Django.
  8. Functions are also :doc:`expressions <expressions>`, so they can be used and
  9. combined with other expressions like :ref:`aggregate functions
  10. <aggregation-functions>`.
  11. We'll be using the following model in examples of each function::
  12. class Author(models.Model):
  13. name = models.CharField(max_length=50)
  14. age = models.PositiveIntegerField(null=True, blank=True)
  15. alias = models.CharField(max_length=50, null=True, blank=True)
  16. goes_by = models.CharField(max_length=50, null=True, blank=True)
  17. We don't usually recommend allowing ``null=True`` for ``CharField`` since this
  18. allows the field to have two "empty values", but it's important for the
  19. ``Coalesce`` example below.
  20. ``Coalesce``
  21. ============
  22. .. class:: Coalesce(*expressions, **extra)
  23. Accepts a list of at least two field names or expressions and returns the
  24. first non-null value (note that an empty string is not considered a null
  25. value). Each argument must be of a similar type, so mixing text and numbers
  26. will result in a database error.
  27. Usage examples::
  28. >>> # Get a screen name from least to most public
  29. >>> from django.db.models import Sum, Value as V
  30. >>> from django.db.models.functions import Coalesce
  31. >>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')
  32. >>> author = Author.objects.annotate(
  33. ... screen_name=Coalesce('alias', 'goes_by', 'name')).get()
  34. >>> print(author.screen_name)
  35. Maggie
  36. >>> # Prevent an aggregate Sum() from returning None
  37. >>> aggregated = Author.objects.aggregate(
  38. ... combined_age=Coalesce(Sum('age'), V(0)),
  39. ... combined_age_default=Sum('age'))
  40. >>> print(aggregated['combined_age'])
  41. 0
  42. >>> print(aggregated['combined_age_default'])
  43. None
  44. .. warning::
  45. A Python value passed to ``Coalesce`` on MySQL may be converted to an
  46. incorrect type unless explicitly cast to the correct database type:
  47. >>> from django.db.models.expressions import RawSQL
  48. >>> from django.utils import timezone
  49. >>> now = timezone.now()
  50. >>> now_sql = RawSQL("cast(%s as datetime)", (now,))
  51. >>> Coalesce('updated', now_sql)
  52. ``Concat``
  53. ==========
  54. .. class:: Concat(*expressions, **extra)
  55. Accepts a list of at least two text fields or expressions and returns the
  56. concatenated text. Each argument must be of a text or char type. If you want
  57. to concatenate a ``TextField()`` with a ``CharField()``, then be sure to tell
  58. Django that the ``output_field`` should be a ``TextField()``. This is also
  59. required when concatenating a ``Value`` as in the example below.
  60. This function will never have a null result. On backends where a null argument
  61. results in the entire expression being null, Django will ensure that each null
  62. part is converted to an empty string first.
  63. Usage example::
  64. >>> # Get the display name as "name (goes_by)"
  65. >>> from django.db.models import CharField, Value as V
  66. >>> from django.db.models.functions import Concat
  67. >>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')
  68. >>> author = Author.objects.annotate(
  69. ... screen_name=Concat('name', V(' ('), 'goes_by', V(')'),
  70. ... output_field=CharField())).get()
  71. >>> print(author.screen_name)
  72. Margaret Smith (Maggie)
  73. ``Greatest``
  74. ============
  75. .. class:: Greatest(*expressions, **extra)
  76. .. versionadded:: 1.9
  77. Accepts a list of at least two field names or expressions and returns the
  78. greatest value. Each argument must be of a similar type, so mixing text and
  79. numbers will result in a database error.
  80. Usage example::
  81. class Blog(models.Model):
  82. body = models.TextField()
  83. modified = models.DateTimeField(auto_now=True)
  84. class Comment(models.Model):
  85. body = models.TextField()
  86. modified = models.DateTimeField(auto_now=True)
  87. blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
  88. >>> from django.db.models.functions import Greatest
  89. >>> blog = Blog.objects.create(body='Greatest is the best.')
  90. >>> comment = Comment.objects.create(body='No, Least is better.', blog=blog)
  91. >>> comments = Comment.objects.annotate(last_updated=Greatest('modified', 'blog__modified'))
  92. >>> annotated_comment = comments.get()
  93. ``annotated_comment.last_updated`` will be the most recent of ``blog.modified``
  94. and ``comment.modified``.
  95. .. warning::
  96. The behavior of ``Greatest`` when one or more expression may be ``null``
  97. varies between databases:
  98. - PostgreSQL: ``Greatest`` will return the largest non-null expression,
  99. or ``null`` if all expressions are ``null``.
  100. - SQLite, Oracle, and MySQL: If any expression is ``null``, ``Greatest``
  101. will return ``null``.
  102. The PostgreSQL behavior can be emulated using ``Coalesce`` if you know
  103. a sensible minimum value to provide as a default.
  104. ``Least``
  105. =========
  106. .. class:: Least(*expressions, **extra)
  107. .. versionadded:: 1.9
  108. Accepts a list of at least two field names or expressions and returns the
  109. least value. Each argument must be of a similar type, so mixing text and numbers
  110. will result in a database error.
  111. .. warning::
  112. The behavior of ``Least`` when one or more expression may be ``null``
  113. varies between databases:
  114. - PostgreSQL: ``Least`` will return the smallest non-null expression,
  115. or ``null`` if all expressions are ``null``.
  116. - SQLite, Oracle, and MySQL: If any expression is ``null``, ``Least``
  117. will return ``null``.
  118. The PostgreSQL behavior can be emulated using ``Coalesce`` if you know
  119. a sensible maximum value to provide as a default.
  120. ``Length``
  121. ==========
  122. .. class:: Length(expression, **extra)
  123. Accepts a single text field or expression and returns the number of characters
  124. the value has. If the expression is null, then the length will also be null.
  125. Usage example::
  126. >>> # Get the length of the name and goes_by fields
  127. >>> from django.db.models.functions import Length
  128. >>> Author.objects.create(name='Margaret Smith')
  129. >>> author = Author.objects.annotate(
  130. ... name_length=Length('name'),
  131. ... goes_by_length=Length('goes_by')).get()
  132. >>> print(author.name_length, author.goes_by_length)
  133. (14, None)
  134. It can also be registered as a transform. For example::
  135. >>> from django.db.models import CharField
  136. >>> from django.db.models.functions import Length
  137. >>> CharField.register_lookup(Length, 'length')
  138. >>> # Get authors whose name is longer than 7 characters
  139. >>> authors = Author.objects.filter(name__length__gt=7)
  140. .. versionchanged:: 1.9
  141. The ability to register the function as a transform was added.
  142. ``Lower``
  143. =========
  144. .. class:: Lower(expression, **extra)
  145. Accepts a single text field or expression and returns the lowercase
  146. representation.
  147. It can also be registered as a transform as described in :class:`Length`.
  148. Usage example::
  149. >>> from django.db.models.functions import Lower
  150. >>> Author.objects.create(name='Margaret Smith')
  151. >>> author = Author.objects.annotate(name_lower=Lower('name')).get()
  152. >>> print(author.name_lower)
  153. margaret smith
  154. .. versionchanged:: 1.9
  155. The ability to register the function as a transform was added.
  156. ``Now``
  157. =======
  158. .. class:: Now()
  159. .. versionadded:: 1.9
  160. Returns the database server's current date and time when the query is executed,
  161. typically using the SQL ``CURRENT_TIMESTAMP``.
  162. Usage example::
  163. >>> from django.db.models.functions import Now
  164. >>> Article.objects.filter(published__lte=Now())
  165. <QuerySet [<Article: How to Django>]>
  166. .. admonition:: PostgreSQL considerations
  167. On PostgreSQL, the SQL ``CURRENT_TIMESTAMP`` returns the time that the
  168. current transaction started. Therefore for cross-database compatibility,
  169. ``Now()`` uses ``STATEMENT_TIMESTAMP`` instead. If you need the transaction
  170. timestamp, use :class:`django.contrib.postgres.functions.TransactionNow`.
  171. ``Substr``
  172. ==========
  173. .. class:: Substr(expression, pos, length=None, **extra)
  174. Returns a substring of length ``length`` from the field or expression starting
  175. at position ``pos``. The position is 1-indexed, so the position must be greater
  176. than 0. If ``length`` is ``None``, then the rest of the string will be returned.
  177. Usage example::
  178. >>> # Set the alias to the first 5 characters of the name as lowercase
  179. >>> from django.db.models.functions import Substr, Lower
  180. >>> Author.objects.create(name='Margaret Smith')
  181. >>> Author.objects.update(alias=Lower(Substr('name', 1, 5)))
  182. 1
  183. >>> print(Author.objects.get(name='Margaret Smith').alias)
  184. marga
  185. ``Upper``
  186. =========
  187. .. class:: Upper(expression, **extra)
  188. Accepts a single text field or expression and returns the uppercase
  189. representation.
  190. It can also be registered as a transform as described in :class:`Length`.
  191. Usage example::
  192. >>> from django.db.models.functions import Upper
  193. >>> Author.objects.create(name='Margaret Smith')
  194. >>> author = Author.objects.annotate(name_upper=Upper('name')).get()
  195. >>> print(author.name_upper)
  196. MARGARET SMITH
  197. .. versionchanged:: 1.9
  198. The ability to register the function as a transform was added.