database-functions.txt 8.3 KB

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