1. ==================
    
  2. Database Functions
    
  3. ==================
    
  4. 
    
  5. .. module:: django.db.models.functions
    
  6.     :synopsis: Database Functions
    
  7. 
    
  8. The classes documented below provide a way for users to use functions provided
    
  9. by the underlying database as annotations, aggregations, or filters in Django.
    
  10. Functions are also :doc:`expressions <expressions>`, so they can be used and
    
  11. combined with other expressions like :ref:`aggregate functions
    
  12. <aggregation-functions>`.
    
  13. 
    
  14. We'll be using the following model in examples of each function::
    
  15. 
    
  16.     class Author(models.Model):
    
  17.         name = models.CharField(max_length=50)
    
  18.         age = models.PositiveIntegerField(null=True, blank=True)
    
  19.         alias = models.CharField(max_length=50, null=True, blank=True)
    
  20.         goes_by = models.CharField(max_length=50, null=True, blank=True)
    
  21. 
    
  22. We don't usually recommend allowing ``null=True`` for ``CharField`` since this
    
  23. allows the field to have two "empty values", but it's important for the
    
  24. ``Coalesce`` example below.
    
  25. 
    
  26. .. _comparison-functions:
    
  27. 
    
  28. Comparison and conversion functions
    
  29. ===================================
    
  30. 
    
  31. ``Cast``
    
  32. --------
    
  33. 
    
  34. .. class:: Cast(expression, output_field)
    
  35. 
    
  36. Forces the result type of ``expression`` to be the one from ``output_field``.
    
  37. 
    
  38. Usage example::
    
  39. 
    
  40.     >>> from django.db.models import FloatField
    
  41.     >>> from django.db.models.functions import Cast
    
  42.     >>> Author.objects.create(age=25, name='Margaret Smith')
    
  43.     >>> author = Author.objects.annotate(
    
  44.     ...    age_as_float=Cast('age', output_field=FloatField()),
    
  45.     ... ).get()
    
  46.     >>> print(author.age_as_float)
    
  47.     25.0
    
  48. 
    
  49. ``Coalesce``
    
  50. ------------
    
  51. 
    
  52. .. class:: Coalesce(*expressions, **extra)
    
  53. 
    
  54. Accepts a list of at least two field names or expressions and returns the
    
  55. first non-null value (note that an empty string is not considered a null
    
  56. value). Each argument must be of a similar type, so mixing text and numbers
    
  57. will result in a database error.
    
  58. 
    
  59. Usage examples::
    
  60. 
    
  61.     >>> # Get a screen name from least to most public
    
  62.     >>> from django.db.models import Sum
    
  63.     >>> from django.db.models.functions import Coalesce
    
  64.     >>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')
    
  65.     >>> author = Author.objects.annotate(
    
  66.     ...    screen_name=Coalesce('alias', 'goes_by', 'name')).get()
    
  67.     >>> print(author.screen_name)
    
  68.     Maggie
    
  69. 
    
  70.     >>> # Prevent an aggregate Sum() from returning None
    
  71.     >>> # The aggregate default argument uses Coalesce() under the hood.
    
  72.     >>> aggregated = Author.objects.aggregate(
    
  73.     ...    combined_age=Sum('age'),
    
  74.     ...    combined_age_default=Sum('age', default=0),
    
  75.     ...    combined_age_coalesce=Coalesce(Sum('age'), 0),
    
  76.     ... )
    
  77.     >>> print(aggregated['combined_age'])
    
  78.     None
    
  79.     >>> print(aggregated['combined_age_default'])
    
  80.     0
    
  81.     >>> print(aggregated['combined_age_coalesce'])
    
  82.     0
    
  83. 
    
  84. .. warning::
    
  85. 
    
  86.     A Python value passed to ``Coalesce`` on MySQL may be converted to an
    
  87.     incorrect type unless explicitly cast to the correct database type:
    
  88. 
    
  89.     >>> from django.db.models import DateTimeField
    
  90.     >>> from django.db.models.functions import Cast, Coalesce
    
  91.     >>> from django.utils import timezone
    
  92.     >>> now = timezone.now()
    
  93.     >>> Coalesce('updated', Cast(now, DateTimeField()))
    
  94. 
    
  95. ``Collate``
    
  96. -----------
    
  97. 
    
  98. .. class:: Collate(expression, collation)
    
  99. 
    
  100. Takes an expression and a collation name to query against.
    
  101. 
    
  102. For example, to filter case-insensitively in SQLite::
    
  103. 
    
  104.     >>> Author.objects.filter(name=Collate(Value('john'), 'nocase'))
    
  105.     <QuerySet [<Author: John>, <Author: john>]>
    
  106. 
    
  107. It can also be used when ordering, for example with PostgreSQL::
    
  108. 
    
  109.     >>> Author.objects.order_by(Collate('name', 'et-x-icu'))
    
  110.     <QuerySet [<Author: Ursula>, <Author: Veronika>, <Author: Ülle>]>
    
  111. 
    
  112. ``Greatest``
    
  113. ------------
    
  114. 
    
  115. .. class:: Greatest(*expressions, **extra)
    
  116. 
    
  117. Accepts a list of at least two field names or expressions and returns the
    
  118. greatest value. Each argument must be of a similar type, so mixing text and
    
  119. numbers will result in a database error.
    
  120. 
    
  121. Usage example::
    
  122. 
    
  123.     class Blog(models.Model):
    
  124.         body = models.TextField()
    
  125.         modified = models.DateTimeField(auto_now=True)
    
  126. 
    
  127.     class Comment(models.Model):
    
  128.         body = models.TextField()
    
  129.         modified = models.DateTimeField(auto_now=True)
    
  130.         blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    
  131. 
    
  132.     >>> from django.db.models.functions import Greatest
    
  133.     >>> blog = Blog.objects.create(body='Greatest is the best.')
    
  134.     >>> comment = Comment.objects.create(body='No, Least is better.', blog=blog)
    
  135.     >>> comments = Comment.objects.annotate(last_updated=Greatest('modified', 'blog__modified'))
    
  136.     >>> annotated_comment = comments.get()
    
  137. 
    
  138. ``annotated_comment.last_updated`` will be the most recent of ``blog.modified``
    
  139. and ``comment.modified``.
    
  140. 
    
  141. .. warning::
    
  142. 
    
  143.     The behavior of ``Greatest`` when one or more expression may be ``null``
    
  144.     varies between databases:
    
  145. 
    
  146.     - PostgreSQL: ``Greatest`` will return the largest non-null expression,
    
  147.       or ``null`` if all expressions are ``null``.
    
  148.     - SQLite, Oracle, and MySQL: If any expression is ``null``, ``Greatest``
    
  149.       will return ``null``.
    
  150. 
    
  151.     The PostgreSQL behavior can be emulated using ``Coalesce`` if you know
    
  152.     a sensible minimum value to provide as a default.
    
  153. 
    
  154. ``JSONObject``
    
  155. --------------
    
  156. 
    
  157. .. class:: JSONObject(**fields)
    
  158. 
    
  159. Takes a list of key-value pairs and returns a JSON object containing those
    
  160. pairs.
    
  161. 
    
  162. Usage example::
    
  163. 
    
  164.     >>> from django.db.models import F
    
  165.     >>> from django.db.models.functions import JSONObject, Lower
    
  166.     >>> Author.objects.create(name='Margaret Smith', alias='msmith', age=25)
    
  167.     >>> author = Author.objects.annotate(json_object=JSONObject(
    
  168.     ...     name=Lower('name'),
    
  169.     ...     alias='alias',
    
  170.     ...     age=F('age') * 2,
    
  171.     ... )).get()
    
  172.     >>> author.json_object
    
  173.     {'name': 'margaret smith', 'alias': 'msmith', 'age': 50}
    
  174. 
    
  175. ``Least``
    
  176. ---------
    
  177. 
    
  178. .. class:: Least(*expressions, **extra)
    
  179. 
    
  180. Accepts a list of at least two field names or expressions and returns the
    
  181. least value. Each argument must be of a similar type, so mixing text and numbers
    
  182. will result in a database error.
    
  183. 
    
  184. .. warning::
    
  185. 
    
  186.     The behavior of ``Least`` when one or more expression may be ``null``
    
  187.     varies between databases:
    
  188. 
    
  189.     - PostgreSQL: ``Least`` will return the smallest non-null expression,
    
  190.       or ``null`` if all expressions are ``null``.
    
  191.     - SQLite, Oracle, and MySQL: If any expression is ``null``, ``Least``
    
  192.       will return ``null``.
    
  193. 
    
  194.     The PostgreSQL behavior can be emulated using ``Coalesce`` if you know
    
  195.     a sensible maximum value to provide as a default.
    
  196. 
    
  197. ``NullIf``
    
  198. ----------
    
  199. 
    
  200. .. class:: NullIf(expression1, expression2)
    
  201. 
    
  202. Accepts two expressions and returns ``None`` if they are equal, otherwise
    
  203. returns ``expression1``.
    
  204. 
    
  205. .. admonition:: Caveats on Oracle
    
  206. 
    
  207.     Due to an :ref:`Oracle convention<oracle-null-empty-strings>`, this
    
  208.     function returns the empty string instead of ``None`` when the expressions
    
  209.     are of type :class:`~django.db.models.CharField`.
    
  210. 
    
  211.     Passing ``Value(None)`` to ``expression1`` is prohibited on Oracle since
    
  212.     Oracle doesn't accept ``NULL`` as the first argument.
    
  213. 
    
  214. .. _date-functions:
    
  215. 
    
  216. Date functions
    
  217. ==============
    
  218. 
    
  219. We'll be using the following model in examples of each function::
    
  220. 
    
  221.     class Experiment(models.Model):
    
  222.         start_datetime = models.DateTimeField()
    
  223.         start_date = models.DateField(null=True, blank=True)
    
  224.         start_time = models.TimeField(null=True, blank=True)
    
  225.         end_datetime = models.DateTimeField(null=True, blank=True)
    
  226.         end_date = models.DateField(null=True, blank=True)
    
  227.         end_time = models.TimeField(null=True, blank=True)
    
  228. 
    
  229. ``Extract``
    
  230. -----------
    
  231. 
    
  232. .. class:: Extract(expression, lookup_name=None, tzinfo=None, **extra)
    
  233. 
    
  234. Extracts a component of a date as a number.
    
  235. 
    
  236. Takes an ``expression`` representing a ``DateField``, ``DateTimeField``,
    
  237. ``TimeField``, or ``DurationField`` and a ``lookup_name``, and returns the part
    
  238. of the date referenced by ``lookup_name`` as an ``IntegerField``.
    
  239. Django usually uses the databases' extract function, so you may use any
    
  240. ``lookup_name`` that your database supports. A ``tzinfo`` subclass, usually
    
  241. provided by :mod:`zoneinfo`, can be passed to extract a value in a specific
    
  242. timezone.
    
  243. 
    
  244. Given the datetime ``2015-06-15 23:30:01.000321+00:00``, the built-in
    
  245. ``lookup_name``\s return:
    
  246. 
    
  247. * "year": 2015
    
  248. * "iso_year": 2015
    
  249. * "quarter": 2
    
  250. * "month": 6
    
  251. * "day": 15
    
  252. * "week": 25
    
  253. * "week_day": 2
    
  254. * "iso_week_day": 1
    
  255. * "hour": 23
    
  256. * "minute": 30
    
  257. * "second": 1
    
  258. 
    
  259. If a different timezone like ``Australia/Melbourne`` is active in Django, then
    
  260. the datetime is converted to the timezone before the value is extracted. The
    
  261. timezone offset for Melbourne in the example date above is +10:00. The values
    
  262. returned when this timezone is active will be the same as above except for:
    
  263. 
    
  264. * "day": 16
    
  265. * "week_day": 3
    
  266. * "iso_week_day": 2
    
  267. * "hour": 9
    
  268. 
    
  269. .. admonition:: ``week_day`` values
    
  270. 
    
  271.     The ``week_day`` ``lookup_type`` is calculated differently from most
    
  272.     databases and from Python's standard functions. This function will return
    
  273.     ``1`` for Sunday, ``2`` for Monday, through ``7`` for Saturday.
    
  274. 
    
  275.     The equivalent calculation in Python is::
    
  276. 
    
  277.         >>> from datetime import datetime
    
  278.         >>> dt = datetime(2015, 6, 15)
    
  279.         >>> (dt.isoweekday() % 7) + 1
    
  280.         2
    
  281. 
    
  282. .. admonition:: ``week`` values
    
  283. 
    
  284.     The ``week`` ``lookup_type`` is calculated based on `ISO-8601
    
  285.     <https://en.wikipedia.org/wiki/ISO-8601>`_, i.e.,
    
  286.     a week starts on a Monday. The first week of a year is the one that
    
  287.     contains the year's first Thursday, i.e. the first week has the majority
    
  288.     (four or more) of its days in the year. The value returned is in the range
    
  289.     1 to 52 or 53.
    
  290. 
    
  291. Each ``lookup_name`` above has a corresponding ``Extract`` subclass (listed
    
  292. below) that should typically be used instead of the more verbose equivalent,
    
  293. e.g. use ``ExtractYear(...)`` rather than ``Extract(..., lookup_name='year')``.
    
  294. 
    
  295. Usage example::
    
  296. 
    
  297.     >>> from datetime import datetime
    
  298.     >>> from django.db.models.functions import Extract
    
  299.     >>> start = datetime(2015, 6, 15)
    
  300.     >>> end = datetime(2015, 7, 2)
    
  301.     >>> Experiment.objects.create(
    
  302.     ...    start_datetime=start, start_date=start.date(),
    
  303.     ...    end_datetime=end, end_date=end.date())
    
  304.     >>> # Add the experiment start year as a field in the QuerySet.
    
  305.     >>> experiment = Experiment.objects.annotate(
    
  306.     ...    start_year=Extract('start_datetime', 'year')).get()
    
  307.     >>> experiment.start_year
    
  308.     2015
    
  309.     >>> # How many experiments completed in the same year in which they started?
    
  310.     >>> Experiment.objects.filter(
    
  311.     ...    start_datetime__year=Extract('end_datetime', 'year')).count()
    
  312.     1
    
  313. 
    
  314. ``DateField`` extracts
    
  315. ~~~~~~~~~~~~~~~~~~~~~~
    
  316. 
    
  317. .. class:: ExtractYear(expression, tzinfo=None, **extra)
    
  318. 
    
  319.     .. attribute:: lookup_name = 'year'
    
  320. 
    
  321. .. class:: ExtractIsoYear(expression, tzinfo=None, **extra)
    
  322. 
    
  323.     Returns the ISO-8601 week-numbering year.
    
  324. 
    
  325.     .. attribute:: lookup_name = 'iso_year'
    
  326. 
    
  327. .. class:: ExtractMonth(expression, tzinfo=None, **extra)
    
  328. 
    
  329.     .. attribute:: lookup_name = 'month'
    
  330. 
    
  331. .. class:: ExtractDay(expression, tzinfo=None, **extra)
    
  332. 
    
  333.     .. attribute:: lookup_name = 'day'
    
  334. 
    
  335. .. class:: ExtractWeekDay(expression, tzinfo=None, **extra)
    
  336. 
    
  337.     .. attribute:: lookup_name = 'week_day'
    
  338. 
    
  339. .. class:: ExtractIsoWeekDay(expression, tzinfo=None, **extra)
    
  340. 
    
  341.     Returns the ISO-8601 week day with day 1 being Monday and day 7 being
    
  342.     Sunday.
    
  343. 
    
  344.     .. attribute:: lookup_name = 'iso_week_day'
    
  345. 
    
  346. .. class:: ExtractWeek(expression, tzinfo=None, **extra)
    
  347. 
    
  348.     .. attribute:: lookup_name = 'week'
    
  349. 
    
  350. .. class:: ExtractQuarter(expression, tzinfo=None, **extra)
    
  351. 
    
  352.     .. attribute:: lookup_name = 'quarter'
    
  353. 
    
  354. These are logically equivalent to ``Extract('date_field', lookup_name)``. Each
    
  355. class is also a ``Transform`` registered on ``DateField`` and ``DateTimeField``
    
  356. as ``__(lookup_name)``, e.g. ``__year``.
    
  357. 
    
  358. Since ``DateField``\s don't have a time component, only ``Extract`` subclasses
    
  359. that deal with date-parts can be used with ``DateField``::
    
  360. 
    
  361.     >>> from datetime import datetime, timezone
    
  362.     >>> from django.db.models.functions import (
    
  363.     ...     ExtractDay, ExtractMonth, ExtractQuarter, ExtractWeek,
    
  364.     ...     ExtractIsoWeekDay, ExtractWeekDay, ExtractIsoYear, ExtractYear,
    
  365.     ... )
    
  366.     >>> start_2015 = datetime(2015, 6, 15, 23, 30, 1, tzinfo=timezone.utc)
    
  367.     >>> end_2015 = datetime(2015, 6, 16, 13, 11, 27, tzinfo=timezone.utc)
    
  368.     >>> Experiment.objects.create(
    
  369.     ...    start_datetime=start_2015, start_date=start_2015.date(),
    
  370.     ...    end_datetime=end_2015, end_date=end_2015.date())
    
  371.     >>> Experiment.objects.annotate(
    
  372.     ...     year=ExtractYear('start_date'),
    
  373.     ...     isoyear=ExtractIsoYear('start_date'),
    
  374.     ...     quarter=ExtractQuarter('start_date'),
    
  375.     ...     month=ExtractMonth('start_date'),
    
  376.     ...     week=ExtractWeek('start_date'),
    
  377.     ...     day=ExtractDay('start_date'),
    
  378.     ...     weekday=ExtractWeekDay('start_date'),
    
  379.     ...     isoweekday=ExtractIsoWeekDay('start_date'),
    
  380.     ... ).values(
    
  381.     ...     'year', 'isoyear', 'quarter', 'month', 'week', 'day', 'weekday',
    
  382.     ...     'isoweekday',
    
  383.     ... ).get(end_date__year=ExtractYear('start_date'))
    
  384.     {'year': 2015, 'isoyear': 2015, 'quarter': 2, 'month': 6, 'week': 25,
    
  385.      'day': 15, 'weekday': 2, 'isoweekday': 1}
    
  386. 
    
  387. ``DateTimeField`` extracts
    
  388. ~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  389. 
    
  390. In addition to the following, all extracts for ``DateField`` listed above may
    
  391. also be used on ``DateTimeField``\s .
    
  392. 
    
  393. .. class:: ExtractHour(expression, tzinfo=None, **extra)
    
  394. 
    
  395.     .. attribute:: lookup_name = 'hour'
    
  396. 
    
  397. .. class:: ExtractMinute(expression, tzinfo=None, **extra)
    
  398. 
    
  399.     .. attribute:: lookup_name = 'minute'
    
  400. 
    
  401. .. class:: ExtractSecond(expression, tzinfo=None, **extra)
    
  402. 
    
  403.     .. attribute:: lookup_name = 'second'
    
  404. 
    
  405. These are logically equivalent to ``Extract('datetime_field', lookup_name)``.
    
  406. Each class is also a ``Transform`` registered on ``DateTimeField`` as
    
  407. ``__(lookup_name)``, e.g. ``__minute``.
    
  408. 
    
  409. ``DateTimeField`` examples::
    
  410. 
    
  411.     >>> from datetime import datetime, timezone
    
  412.     >>> from django.db.models.functions import (
    
  413.     ...     ExtractDay, ExtractHour, ExtractMinute, ExtractMonth,
    
  414.     ...     ExtractQuarter, ExtractSecond, ExtractWeek, ExtractIsoWeekDay,
    
  415.     ...     ExtractWeekDay, ExtractIsoYear, ExtractYear,
    
  416.     ... )
    
  417.     >>> start_2015 = datetime(2015, 6, 15, 23, 30, 1, tzinfo=timezone.utc)
    
  418.     >>> end_2015 = datetime(2015, 6, 16, 13, 11, 27, tzinfo=timezone.utc)
    
  419.     >>> Experiment.objects.create(
    
  420.     ...    start_datetime=start_2015, start_date=start_2015.date(),
    
  421.     ...    end_datetime=end_2015, end_date=end_2015.date())
    
  422.     >>> Experiment.objects.annotate(
    
  423.     ...     year=ExtractYear('start_datetime'),
    
  424.     ...     isoyear=ExtractIsoYear('start_datetime'),
    
  425.     ...     quarter=ExtractQuarter('start_datetime'),
    
  426.     ...     month=ExtractMonth('start_datetime'),
    
  427.     ...     week=ExtractWeek('start_datetime'),
    
  428.     ...     day=ExtractDay('start_datetime'),
    
  429.     ...     weekday=ExtractWeekDay('start_datetime'),
    
  430.     ...     isoweekday=ExtractIsoWeekDay('start_datetime'),
    
  431.     ...     hour=ExtractHour('start_datetime'),
    
  432.     ...     minute=ExtractMinute('start_datetime'),
    
  433.     ...     second=ExtractSecond('start_datetime'),
    
  434.     ... ).values(
    
  435.     ...     'year', 'isoyear', 'month', 'week', 'day',
    
  436.     ...     'weekday', 'isoweekday', 'hour', 'minute', 'second',
    
  437.     ... ).get(end_datetime__year=ExtractYear('start_datetime'))
    
  438.     {'year': 2015, 'isoyear': 2015, 'quarter': 2, 'month': 6, 'week': 25,
    
  439.      'day': 15, 'weekday': 2, 'isoweekday': 1, 'hour': 23, 'minute': 30,
    
  440.      'second': 1}
    
  441. 
    
  442. When :setting:`USE_TZ` is ``True`` then datetimes are stored in the database
    
  443. in UTC. If a different timezone is active in Django, the datetime is converted
    
  444. to that timezone before the value is extracted. The example below converts to
    
  445. the Melbourne timezone (UTC +10:00), which changes the day, weekday, and hour
    
  446. values that are returned::
    
  447. 
    
  448.     >>> from django.utils import timezone
    
  449.     >>> import zoneinfo
    
  450.     >>> melb = zoneinfo.ZoneInfo('Australia/Melbourne')  # UTC+10:00
    
  451.     >>> with timezone.override(melb):
    
  452.     ...    Experiment.objects.annotate(
    
  453.     ...        day=ExtractDay('start_datetime'),
    
  454.     ...        weekday=ExtractWeekDay('start_datetime'),
    
  455.     ...        isoweekday=ExtractIsoWeekDay('start_datetime'),
    
  456.     ...        hour=ExtractHour('start_datetime'),
    
  457.     ...    ).values('day', 'weekday', 'isoweekday', 'hour').get(
    
  458.     ...        end_datetime__year=ExtractYear('start_datetime'),
    
  459.     ...    )
    
  460.     {'day': 16, 'weekday': 3, 'isoweekday': 2, 'hour': 9}
    
  461. 
    
  462. Explicitly passing the timezone to the ``Extract`` function behaves in the same
    
  463. way, and takes priority over an active timezone::
    
  464. 
    
  465.     >>> import zoneinfo
    
  466.     >>> melb = zoneinfo.ZoneInfo('Australia/Melbourne')
    
  467.     >>> Experiment.objects.annotate(
    
  468.     ...     day=ExtractDay('start_datetime', tzinfo=melb),
    
  469.     ...     weekday=ExtractWeekDay('start_datetime', tzinfo=melb),
    
  470.     ...     isoweekday=ExtractIsoWeekDay('start_datetime', tzinfo=melb),
    
  471.     ...     hour=ExtractHour('start_datetime', tzinfo=melb),
    
  472.     ... ).values('day', 'weekday', 'isoweekday', 'hour').get(
    
  473.     ...     end_datetime__year=ExtractYear('start_datetime'),
    
  474.     ... )
    
  475.     {'day': 16, 'weekday': 3, 'isoweekday': 2, 'hour': 9}
    
  476. 
    
  477. ``Now``
    
  478. -------
    
  479. 
    
  480. .. class:: Now()
    
  481. 
    
  482. Returns the database server's current date and time when the query is executed,
    
  483. typically using the SQL ``CURRENT_TIMESTAMP``.
    
  484. 
    
  485. Usage example::
    
  486. 
    
  487.     >>> from django.db.models.functions import Now
    
  488.     >>> Article.objects.filter(published__lte=Now())
    
  489.     <QuerySet [<Article: How to Django>]>
    
  490. 
    
  491. .. admonition:: PostgreSQL considerations
    
  492. 
    
  493.     On PostgreSQL, the SQL ``CURRENT_TIMESTAMP`` returns the time that the
    
  494.     current transaction started. Therefore for cross-database compatibility,
    
  495.     ``Now()`` uses ``STATEMENT_TIMESTAMP`` instead. If you need the transaction
    
  496.     timestamp, use :class:`django.contrib.postgres.functions.TransactionNow`.
    
  497. 
    
  498. ``Trunc``
    
  499. ---------
    
  500. 
    
  501. .. class:: Trunc(expression, kind, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  502. 
    
  503. Truncates a date up to a significant component.
    
  504. 
    
  505. When you only care if something happened in a particular year, hour, or day,
    
  506. but not the exact second, then ``Trunc`` (and its subclasses) can be useful to
    
  507. filter or aggregate your data. For example, you can use ``Trunc`` to calculate
    
  508. the number of sales per day.
    
  509. 
    
  510. ``Trunc`` takes a single ``expression``, representing a ``DateField``,
    
  511. ``TimeField``, or ``DateTimeField``, a ``kind`` representing a date or time
    
  512. part, and an ``output_field`` that's either ``DateTimeField()``,
    
  513. ``TimeField()``, or ``DateField()``. It returns a datetime, date, or time
    
  514. depending on ``output_field``, with fields up to ``kind`` set to their minimum
    
  515. value. If ``output_field`` is omitted, it will default to the ``output_field``
    
  516. of ``expression``. A ``tzinfo`` subclass, usually provided by :mod:`zoneinfo`,
    
  517. can be passed to truncate a value in a specific timezone.
    
  518. 
    
  519. .. deprecated:: 4.0
    
  520. 
    
  521.     The ``is_dst`` parameter indicates whether or not ``pytz`` should interpret
    
  522.     nonexistent and ambiguous datetimes in daylight saving time. By default
    
  523.     (when ``is_dst=None``), ``pytz`` raises an exception for such datetimes.
    
  524. 
    
  525.     The ``is_dst`` parameter is deprecated and will be removed in Django 5.0.
    
  526. 
    
  527. Given the datetime ``2015-06-15 14:30:50.000321+00:00``, the built-in ``kind``\s
    
  528. return:
    
  529. 
    
  530. * "year": 2015-01-01 00:00:00+00:00
    
  531. * "quarter": 2015-04-01 00:00:00+00:00
    
  532. * "month": 2015-06-01 00:00:00+00:00
    
  533. * "week": 2015-06-15 00:00:00+00:00
    
  534. * "day": 2015-06-15 00:00:00+00:00
    
  535. * "hour": 2015-06-15 14:00:00+00:00
    
  536. * "minute": 2015-06-15 14:30:00+00:00
    
  537. * "second": 2015-06-15 14:30:50+00:00
    
  538. 
    
  539. If a different timezone like ``Australia/Melbourne`` is active in Django, then
    
  540. the datetime is converted to the new timezone before the value is truncated.
    
  541. The timezone offset for Melbourne in the example date above is +10:00. The
    
  542. values returned when this timezone is active will be:
    
  543. 
    
  544. * "year": 2015-01-01 00:00:00+11:00
    
  545. * "quarter": 2015-04-01 00:00:00+10:00
    
  546. * "month": 2015-06-01 00:00:00+10:00
    
  547. * "week": 2015-06-16 00:00:00+10:00
    
  548. * "day": 2015-06-16 00:00:00+10:00
    
  549. * "hour": 2015-06-16 00:00:00+10:00
    
  550. * "minute": 2015-06-16 00:30:00+10:00
    
  551. * "second": 2015-06-16 00:30:50+10:00
    
  552. 
    
  553. The year has an offset of +11:00 because the result transitioned into daylight
    
  554. saving time.
    
  555. 
    
  556. Each ``kind`` above has a corresponding ``Trunc`` subclass (listed below) that
    
  557. should typically be used instead of the more verbose equivalent,
    
  558. e.g. use ``TruncYear(...)`` rather than ``Trunc(..., kind='year')``.
    
  559. 
    
  560. The subclasses are all defined as transforms, but they aren't registered with
    
  561. any fields, because the lookup names are already reserved by the ``Extract``
    
  562. subclasses.
    
  563. 
    
  564. Usage example::
    
  565. 
    
  566.     >>> from datetime import datetime
    
  567.     >>> from django.db.models import Count, DateTimeField
    
  568.     >>> from django.db.models.functions import Trunc
    
  569.     >>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 30, 50, 321))
    
  570.     >>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 40, 2, 123))
    
  571.     >>> Experiment.objects.create(start_datetime=datetime(2015, 12, 25, 10, 5, 27, 999))
    
  572.     >>> experiments_per_day = Experiment.objects.annotate(
    
  573.     ...    start_day=Trunc('start_datetime', 'day', output_field=DateTimeField())
    
  574.     ... ).values('start_day').annotate(experiments=Count('id'))
    
  575.     >>> for exp in experiments_per_day:
    
  576.     ...     print(exp['start_day'], exp['experiments'])
    
  577.     ...
    
  578.     2015-06-15 00:00:00 2
    
  579.     2015-12-25 00:00:00 1
    
  580.     >>> experiments = Experiment.objects.annotate(
    
  581.     ...    start_day=Trunc('start_datetime', 'day', output_field=DateTimeField())
    
  582.     ... ).filter(start_day=datetime(2015, 6, 15))
    
  583.     >>> for exp in experiments:
    
  584.     ...     print(exp.start_datetime)
    
  585.     ...
    
  586.     2015-06-15 14:30:50.000321
    
  587.     2015-06-15 14:40:02.000123
    
  588. 
    
  589. ``DateField`` truncation
    
  590. ~~~~~~~~~~~~~~~~~~~~~~~~
    
  591. 
    
  592. .. class:: TruncYear(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  593. 
    
  594.     .. attribute:: kind = 'year'
    
  595. 
    
  596. .. class:: TruncMonth(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  597. 
    
  598.     .. attribute:: kind = 'month'
    
  599. 
    
  600. .. class:: TruncWeek(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  601. 
    
  602.     Truncates to midnight on the Monday of the week.
    
  603. 
    
  604.     .. attribute:: kind = 'week'
    
  605. 
    
  606. .. class:: TruncQuarter(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  607. 
    
  608.     .. attribute:: kind = 'quarter'
    
  609. 
    
  610. .. deprecated:: 4.0
    
  611. 
    
  612.     The ``is_dst`` parameter is deprecated and will be removed in Django 5.0.
    
  613. 
    
  614. These are logically equivalent to ``Trunc('date_field', kind)``. They truncate
    
  615. all parts of the date up to ``kind`` which allows grouping or filtering dates
    
  616. with less precision. ``expression`` can have an ``output_field`` of either
    
  617. ``DateField`` or ``DateTimeField``.
    
  618. 
    
  619. Since ``DateField``\s don't have a time component, only ``Trunc`` subclasses
    
  620. that deal with date-parts can be used with ``DateField``::
    
  621. 
    
  622.     >>> from datetime import datetime, timezone
    
  623.     >>> from django.db.models import Count
    
  624.     >>> from django.db.models.functions import TruncMonth, TruncYear
    
  625.     >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
    
  626.     >>> start2 = datetime(2015, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)
    
  627.     >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)
    
  628.     >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
    
  629.     >>> Experiment.objects.create(start_datetime=start2, start_date=start2.date())
    
  630.     >>> Experiment.objects.create(start_datetime=start3, start_date=start3.date())
    
  631.     >>> experiments_per_year = Experiment.objects.annotate(
    
  632.     ...    year=TruncYear('start_date')).values('year').annotate(
    
  633.     ...    experiments=Count('id'))
    
  634.     >>> for exp in experiments_per_year:
    
  635.     ...     print(exp['year'], exp['experiments'])
    
  636.     ...
    
  637.     2014-01-01 1
    
  638.     2015-01-01 2
    
  639. 
    
  640.     >>> import zoneinfo
    
  641.     >>> melb = zoneinfo.ZoneInfo('Australia/Melbourne')
    
  642.     >>> experiments_per_month = Experiment.objects.annotate(
    
  643.     ...    month=TruncMonth('start_datetime', tzinfo=melb)).values('month').annotate(
    
  644.     ...    experiments=Count('id'))
    
  645.     >>> for exp in experiments_per_month:
    
  646.     ...     print(exp['month'], exp['experiments'])
    
  647.     ...
    
  648.     2015-06-01 00:00:00+10:00 1
    
  649.     2016-01-01 00:00:00+11:00 1
    
  650.     2014-06-01 00:00:00+10:00 1
    
  651. 
    
  652. ``DateTimeField`` truncation
    
  653. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
  654. 
    
  655. .. class:: TruncDate(expression, tzinfo=None, **extra)
    
  656. 
    
  657.     .. attribute:: lookup_name = 'date'
    
  658.     .. attribute:: output_field = DateField()
    
  659. 
    
  660. ``TruncDate`` casts ``expression`` to a date rather than using the built-in SQL
    
  661. truncate function. It's also registered as a transform on  ``DateTimeField`` as
    
  662. ``__date``.
    
  663. 
    
  664. .. class:: TruncTime(expression, tzinfo=None, **extra)
    
  665. 
    
  666.     .. attribute:: lookup_name = 'time'
    
  667.     .. attribute:: output_field = TimeField()
    
  668. 
    
  669. ``TruncTime`` casts ``expression`` to a time rather than using the built-in SQL
    
  670. truncate function. It's also registered as a transform on ``DateTimeField`` as
    
  671. ``__time``.
    
  672. 
    
  673. .. class:: TruncDay(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  674. 
    
  675.     .. attribute:: kind = 'day'
    
  676. 
    
  677. .. class:: TruncHour(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  678. 
    
  679.     .. attribute:: kind = 'hour'
    
  680. 
    
  681. .. class:: TruncMinute(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  682. 
    
  683.     .. attribute:: kind = 'minute'
    
  684. 
    
  685. .. class:: TruncSecond(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  686. 
    
  687.     .. attribute:: kind = 'second'
    
  688. 
    
  689. .. deprecated:: 4.0
    
  690. 
    
  691.     The ``is_dst`` parameter is deprecated and will be removed in Django 5.0.
    
  692. 
    
  693. These are logically equivalent to ``Trunc('datetime_field', kind)``. They
    
  694. truncate all parts of the date up to ``kind`` and allow grouping or filtering
    
  695. datetimes with less precision. ``expression`` must have an ``output_field`` of
    
  696. ``DateTimeField``.
    
  697. 
    
  698. Usage example::
    
  699. 
    
  700.     >>> from datetime import date, datetime, timezone
    
  701.     >>> from django.db.models import Count
    
  702.     >>> from django.db.models.functions import (
    
  703.     ...     TruncDate, TruncDay, TruncHour, TruncMinute, TruncSecond,
    
  704.     ... )
    
  705.     >>> import zoneinfo
    
  706.     >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
    
  707.     >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
    
  708.     >>> melb = zoneinfo.ZoneInfo('Australia/Melbourne')
    
  709.     >>> Experiment.objects.annotate(
    
  710.     ...     date=TruncDate('start_datetime'),
    
  711.     ...     day=TruncDay('start_datetime', tzinfo=melb),
    
  712.     ...     hour=TruncHour('start_datetime', tzinfo=melb),
    
  713.     ...     minute=TruncMinute('start_datetime'),
    
  714.     ...     second=TruncSecond('start_datetime'),
    
  715.     ... ).values('date', 'day', 'hour', 'minute', 'second').get()
    
  716.     {'date': datetime.date(2014, 6, 15),
    
  717.      'day': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=zoneinfo.ZoneInfo('Australia/Melbourne')),
    
  718.      'hour': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=zoneinfo.ZoneInfo('Australia/Melbourne')),
    
  719.      'minute': 'minute': datetime.datetime(2014, 6, 15, 14, 30, tzinfo=timezone.utc),
    
  720.      'second': datetime.datetime(2014, 6, 15, 14, 30, 50, tzinfo=timezone.utc)
    
  721.     }
    
  722. 
    
  723. ``TimeField`` truncation
    
  724. ~~~~~~~~~~~~~~~~~~~~~~~~
    
  725. 
    
  726. .. class:: TruncHour(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  727.     :noindex:
    
  728. 
    
  729.     .. attribute:: kind = 'hour'
    
  730. 
    
  731. .. class:: TruncMinute(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  732.     :noindex:
    
  733. 
    
  734.     .. attribute:: kind = 'minute'
    
  735. 
    
  736. .. class:: TruncSecond(expression, output_field=None, tzinfo=None, is_dst=None, **extra)
    
  737.     :noindex:
    
  738. 
    
  739.     .. attribute:: kind = 'second'
    
  740. 
    
  741. .. deprecated:: 4.0
    
  742. 
    
  743.     The ``is_dst`` parameter is deprecated and will be removed in Django 5.0.
    
  744. 
    
  745. These are logically equivalent to ``Trunc('time_field', kind)``. They truncate
    
  746. all parts of the time up to ``kind`` which allows grouping or filtering times
    
  747. with less precision. ``expression`` can have an ``output_field`` of either
    
  748. ``TimeField`` or ``DateTimeField``.
    
  749. 
    
  750. Since ``TimeField``\s don't have a date component, only ``Trunc`` subclasses
    
  751. that deal with time-parts can be used with ``TimeField``::
    
  752. 
    
  753.     >>> from datetime import datetime, timezone
    
  754.     >>> from django.db.models import Count, TimeField
    
  755.     >>> from django.db.models.functions import TruncHour
    
  756.     >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
    
  757.     >>> start2 = datetime(2014, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)
    
  758.     >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)
    
  759.     >>> Experiment.objects.create(start_datetime=start1, start_time=start1.time())
    
  760.     >>> Experiment.objects.create(start_datetime=start2, start_time=start2.time())
    
  761.     >>> Experiment.objects.create(start_datetime=start3, start_time=start3.time())
    
  762.     >>> experiments_per_hour = Experiment.objects.annotate(
    
  763.     ...    hour=TruncHour('start_datetime', output_field=TimeField()),
    
  764.     ... ).values('hour').annotate(experiments=Count('id'))
    
  765.     >>> for exp in experiments_per_hour:
    
  766.     ...     print(exp['hour'], exp['experiments'])
    
  767.     ...
    
  768.     14:00:00 2
    
  769.     17:00:00 1
    
  770. 
    
  771.     >>> import zoneinfo
    
  772.     >>> melb = zoneinfo.ZoneInfo('Australia/Melbourne')
    
  773.     >>> experiments_per_hour = Experiment.objects.annotate(
    
  774.     ...    hour=TruncHour('start_datetime', tzinfo=melb),
    
  775.     ... ).values('hour').annotate(experiments=Count('id'))
    
  776.     >>> for exp in experiments_per_hour:
    
  777.     ...     print(exp['hour'], exp['experiments'])
    
  778.     ...
    
  779.     2014-06-16 00:00:00+10:00 2
    
  780.     2016-01-01 04:00:00+11:00 1
    
  781. 
    
  782. .. _math-functions:
    
  783. 
    
  784. Math Functions
    
  785. ==============
    
  786. 
    
  787. We'll be using the following model in math function examples::
    
  788. 
    
  789.     class Vector(models.Model):
    
  790.         x = models.FloatField()
    
  791.         y = models.FloatField()
    
  792. 
    
  793. ``Abs``
    
  794. -------
    
  795. 
    
  796. .. class:: Abs(expression, **extra)
    
  797. 
    
  798. Returns the absolute value of a numeric field or expression.
    
  799. 
    
  800. Usage example::
    
  801. 
    
  802.     >>> from django.db.models.functions import Abs
    
  803.     >>> Vector.objects.create(x=-0.5, y=1.1)
    
  804.     >>> vector = Vector.objects.annotate(x_abs=Abs('x'), y_abs=Abs('y')).get()
    
  805.     >>> vector.x_abs, vector.y_abs
    
  806.     (0.5, 1.1)
    
  807. 
    
  808. It can also be registered as a transform. For example::
    
  809. 
    
  810.     >>> from django.db.models import FloatField
    
  811.     >>> from django.db.models.functions import Abs
    
  812.     >>> FloatField.register_lookup(Abs)
    
  813.     >>> # Get vectors inside the unit cube
    
  814.     >>> vectors = Vector.objects.filter(x__abs__lt=1, y__abs__lt=1)
    
  815. 
    
  816. ``ACos``
    
  817. --------
    
  818. 
    
  819. .. class:: ACos(expression, **extra)
    
  820. 
    
  821. Returns the arccosine of a numeric field or expression. The expression value
    
  822. must be within the range -1 to 1.
    
  823. 
    
  824. Usage example::
    
  825. 
    
  826.     >>> from django.db.models.functions import ACos
    
  827.     >>> Vector.objects.create(x=0.5, y=-0.9)
    
  828.     >>> vector = Vector.objects.annotate(x_acos=ACos('x'), y_acos=ACos('y')).get()
    
  829.     >>> vector.x_acos, vector.y_acos
    
  830.     (1.0471975511965979, 2.6905658417935308)
    
  831. 
    
  832. It can also be registered as a transform. For example::
    
  833. 
    
  834.     >>> from django.db.models import FloatField
    
  835.     >>> from django.db.models.functions import ACos
    
  836.     >>> FloatField.register_lookup(ACos)
    
  837.     >>> # Get vectors whose arccosine is less than 1
    
  838.     >>> vectors = Vector.objects.filter(x__acos__lt=1, y__acos__lt=1)
    
  839. 
    
  840. ``ASin``
    
  841. --------
    
  842. 
    
  843. .. class:: ASin(expression, **extra)
    
  844. 
    
  845. Returns the arcsine of a numeric field or expression. The expression value must
    
  846. be in the range -1 to 1.
    
  847. 
    
  848. Usage example::
    
  849. 
    
  850.     >>> from django.db.models.functions import ASin
    
  851.     >>> Vector.objects.create(x=0, y=1)
    
  852.     >>> vector = Vector.objects.annotate(x_asin=ASin('x'), y_asin=ASin('y')).get()
    
  853.     >>> vector.x_asin, vector.y_asin
    
  854.     (0.0, 1.5707963267948966)
    
  855. 
    
  856. It can also be registered as a transform. For example::
    
  857. 
    
  858.     >>> from django.db.models import FloatField
    
  859.     >>> from django.db.models.functions import ASin
    
  860.     >>> FloatField.register_lookup(ASin)
    
  861.     >>> # Get vectors whose arcsine is less than 1
    
  862.     >>> vectors = Vector.objects.filter(x__asin__lt=1, y__asin__lt=1)
    
  863. 
    
  864. ``ATan``
    
  865. --------
    
  866. 
    
  867. .. class:: ATan(expression, **extra)
    
  868. 
    
  869. Returns the arctangent of a numeric field or expression.
    
  870. 
    
  871. Usage example::
    
  872. 
    
  873.     >>> from django.db.models.functions import ATan
    
  874.     >>> Vector.objects.create(x=3.12, y=6.987)
    
  875.     >>> vector = Vector.objects.annotate(x_atan=ATan('x'), y_atan=ATan('y')).get()
    
  876.     >>> vector.x_atan, vector.y_atan
    
  877.     (1.2606282660069106, 1.428638798133829)
    
  878. 
    
  879. It can also be registered as a transform. For example::
    
  880. 
    
  881.     >>> from django.db.models import FloatField
    
  882.     >>> from django.db.models.functions import ATan
    
  883.     >>> FloatField.register_lookup(ATan)
    
  884.     >>> # Get vectors whose arctangent is less than 2
    
  885.     >>> vectors = Vector.objects.filter(x__atan__lt=2, y__atan__lt=2)
    
  886. 
    
  887. ``ATan2``
    
  888. ---------
    
  889. 
    
  890. .. class:: ATan2(expression1, expression2, **extra)
    
  891. 
    
  892. Returns the arctangent of ``expression1 / expression2``.
    
  893. 
    
  894. Usage example::
    
  895. 
    
  896.     >>> from django.db.models.functions import ATan2
    
  897.     >>> Vector.objects.create(x=2.5, y=1.9)
    
  898.     >>> vector = Vector.objects.annotate(atan2=ATan2('x', 'y')).get()
    
  899.     >>> vector.atan2
    
  900.     0.9209258773829491
    
  901. 
    
  902. ``Ceil``
    
  903. --------
    
  904. 
    
  905. .. class:: Ceil(expression, **extra)
    
  906. 
    
  907. Returns the smallest integer greater than or equal to a numeric field or
    
  908. expression.
    
  909. 
    
  910. Usage example::
    
  911. 
    
  912.     >>> from django.db.models.functions import Ceil
    
  913.     >>> Vector.objects.create(x=3.12, y=7.0)
    
  914.     >>> vector = Vector.objects.annotate(x_ceil=Ceil('x'), y_ceil=Ceil('y')).get()
    
  915.     >>> vector.x_ceil, vector.y_ceil
    
  916.     (4.0, 7.0)
    
  917. 
    
  918. It can also be registered as a transform. For example::
    
  919. 
    
  920.     >>> from django.db.models import FloatField
    
  921.     >>> from django.db.models.functions import Ceil
    
  922.     >>> FloatField.register_lookup(Ceil)
    
  923.     >>> # Get vectors whose ceil is less than 10
    
  924.     >>> vectors = Vector.objects.filter(x__ceil__lt=10, y__ceil__lt=10)
    
  925. 
    
  926. ``Cos``
    
  927. -------
    
  928. 
    
  929. .. class:: Cos(expression, **extra)
    
  930. 
    
  931. Returns the cosine  of a numeric field or expression.
    
  932. 
    
  933. Usage example::
    
  934. 
    
  935.     >>> from django.db.models.functions import Cos
    
  936.     >>> Vector.objects.create(x=-8.0, y=3.1415926)
    
  937.     >>> vector = Vector.objects.annotate(x_cos=Cos('x'), y_cos=Cos('y')).get()
    
  938.     >>> vector.x_cos, vector.y_cos
    
  939.     (-0.14550003380861354, -0.9999999999999986)
    
  940. 
    
  941. It can also be registered as a transform. For example::
    
  942. 
    
  943.     >>> from django.db.models import FloatField
    
  944.     >>> from django.db.models.functions import Cos
    
  945.     >>> FloatField.register_lookup(Cos)
    
  946.     >>> # Get vectors whose cosine is less than 0.5
    
  947.     >>> vectors = Vector.objects.filter(x__cos__lt=0.5, y__cos__lt=0.5)
    
  948. 
    
  949. ``Cot``
    
  950. -------
    
  951. 
    
  952. .. class:: Cot(expression, **extra)
    
  953. 
    
  954. Returns the cotangent of a numeric field or expression.
    
  955. 
    
  956. Usage example::
    
  957. 
    
  958.     >>> from django.db.models.functions import Cot
    
  959.     >>> Vector.objects.create(x=12.0, y=1.0)
    
  960.     >>> vector = Vector.objects.annotate(x_cot=Cot('x'), y_cot=Cot('y')).get()
    
  961.     >>> vector.x_cot, vector.y_cot
    
  962.     (-1.5726734063976826, 0.642092615934331)
    
  963. 
    
  964. It can also be registered as a transform. For example::
    
  965. 
    
  966.     >>> from django.db.models import FloatField
    
  967.     >>> from django.db.models.functions import Cot
    
  968.     >>> FloatField.register_lookup(Cot)
    
  969.     >>> # Get vectors whose cotangent is less than 1
    
  970.     >>> vectors = Vector.objects.filter(x__cot__lt=1, y__cot__lt=1)
    
  971. 
    
  972. ``Degrees``
    
  973. -----------
    
  974. 
    
  975. .. class:: Degrees(expression, **extra)
    
  976. 
    
  977. Converts a numeric field or expression from radians to degrees.
    
  978. 
    
  979. Usage example::
    
  980. 
    
  981.     >>> from django.db.models.functions import Degrees
    
  982.     >>> Vector.objects.create(x=-1.57, y=3.14)
    
  983.     >>> vector = Vector.objects.annotate(x_d=Degrees('x'), y_d=Degrees('y')).get()
    
  984.     >>> vector.x_d, vector.y_d
    
  985.     (-89.95437383553924, 179.9087476710785)
    
  986. 
    
  987. It can also be registered as a transform. For example::
    
  988. 
    
  989.     >>> from django.db.models import FloatField
    
  990.     >>> from django.db.models.functions import Degrees
    
  991.     >>> FloatField.register_lookup(Degrees)
    
  992.     >>> # Get vectors whose degrees are less than 360
    
  993.     >>> vectors = Vector.objects.filter(x__degrees__lt=360, y__degrees__lt=360)
    
  994. 
    
  995. ``Exp``
    
  996. -------
    
  997. 
    
  998. .. class:: Exp(expression, **extra)
    
  999. 
    
  1000. Returns the value of ``e`` (the natural logarithm base) raised to the power of
    
  1001. a numeric field or expression.
    
  1002. 
    
  1003. Usage example::
    
  1004. 
    
  1005.     >>> from django.db.models.functions import Exp
    
  1006.     >>> Vector.objects.create(x=5.4, y=-2.0)
    
  1007.     >>> vector = Vector.objects.annotate(x_exp=Exp('x'), y_exp=Exp('y')).get()
    
  1008.     >>> vector.x_exp, vector.y_exp
    
  1009.     (221.40641620418717, 0.1353352832366127)
    
  1010. 
    
  1011. It can also be registered as a transform. For example::
    
  1012. 
    
  1013.     >>> from django.db.models import FloatField
    
  1014.     >>> from django.db.models.functions import Exp
    
  1015.     >>> FloatField.register_lookup(Exp)
    
  1016.     >>> # Get vectors whose exp() is greater than 10
    
  1017.     >>> vectors = Vector.objects.filter(x__exp__gt=10, y__exp__gt=10)
    
  1018. 
    
  1019. ``Floor``
    
  1020. ---------
    
  1021. 
    
  1022. .. class:: Floor(expression, **extra)
    
  1023. 
    
  1024. Returns the largest integer value not greater than a numeric field or
    
  1025. expression.
    
  1026. 
    
  1027. Usage example::
    
  1028. 
    
  1029.     >>> from django.db.models.functions import Floor
    
  1030.     >>> Vector.objects.create(x=5.4, y=-2.3)
    
  1031.     >>> vector = Vector.objects.annotate(x_floor=Floor('x'), y_floor=Floor('y')).get()
    
  1032.     >>> vector.x_floor, vector.y_floor
    
  1033.     (5.0, -3.0)
    
  1034. 
    
  1035. It can also be registered as a transform. For example::
    
  1036. 
    
  1037.     >>> from django.db.models import FloatField
    
  1038.     >>> from django.db.models.functions import Floor
    
  1039.     >>> FloatField.register_lookup(Floor)
    
  1040.     >>> # Get vectors whose floor() is greater than 10
    
  1041.     >>> vectors = Vector.objects.filter(x__floor__gt=10, y__floor__gt=10)
    
  1042. 
    
  1043. ``Ln``
    
  1044. ------
    
  1045. 
    
  1046. .. class:: Ln(expression, **extra)
    
  1047. 
    
  1048. Returns the natural logarithm a numeric field or expression.
    
  1049. 
    
  1050. Usage example::
    
  1051. 
    
  1052.     >>> from django.db.models.functions import Ln
    
  1053.     >>> Vector.objects.create(x=5.4, y=233.0)
    
  1054.     >>> vector = Vector.objects.annotate(x_ln=Ln('x'), y_ln=Ln('y')).get()
    
  1055.     >>> vector.x_ln, vector.y_ln
    
  1056.     (1.6863989535702288, 5.4510384535657)
    
  1057. 
    
  1058. It can also be registered as a transform. For example::
    
  1059. 
    
  1060.     >>> from django.db.models import FloatField
    
  1061.     >>> from django.db.models.functions import Ln
    
  1062.     >>> FloatField.register_lookup(Ln)
    
  1063.     >>> # Get vectors whose value greater than e
    
  1064.     >>> vectors = Vector.objects.filter(x__ln__gt=1, y__ln__gt=1)
    
  1065. 
    
  1066. ``Log``
    
  1067. -------
    
  1068. 
    
  1069. .. class:: Log(expression1, expression2, **extra)
    
  1070. 
    
  1071. Accepts two numeric fields or expressions and returns the logarithm of
    
  1072. the first to base of the second.
    
  1073. 
    
  1074. Usage example::
    
  1075. 
    
  1076.     >>> from django.db.models.functions import Log
    
  1077.     >>> Vector.objects.create(x=2.0, y=4.0)
    
  1078.     >>> vector = Vector.objects.annotate(log=Log('x', 'y')).get()
    
  1079.     >>> vector.log
    
  1080.     2.0
    
  1081. 
    
  1082. ``Mod``
    
  1083. -------
    
  1084. 
    
  1085. .. class:: Mod(expression1, expression2, **extra)
    
  1086. 
    
  1087. Accepts two numeric fields or expressions and returns the remainder of
    
  1088. the first divided by the second (modulo operation).
    
  1089. 
    
  1090. Usage example::
    
  1091. 
    
  1092.     >>> from django.db.models.functions import Mod
    
  1093.     >>> Vector.objects.create(x=5.4, y=2.3)
    
  1094.     >>> vector = Vector.objects.annotate(mod=Mod('x', 'y')).get()
    
  1095.     >>> vector.mod
    
  1096.     0.8
    
  1097. 
    
  1098. ``Pi``
    
  1099. ------
    
  1100. 
    
  1101. .. class:: Pi(**extra)
    
  1102. 
    
  1103. Returns the value of the mathematical constant ``π``.
    
  1104. 
    
  1105. ``Power``
    
  1106. ---------
    
  1107. 
    
  1108. .. class:: Power(expression1, expression2, **extra)
    
  1109. 
    
  1110. Accepts two numeric fields or expressions and returns the value of the first
    
  1111. raised to the power of the second.
    
  1112. 
    
  1113. Usage example::
    
  1114. 
    
  1115.     >>> from django.db.models.functions import Power
    
  1116.     >>> Vector.objects.create(x=2, y=-2)
    
  1117.     >>> vector = Vector.objects.annotate(power=Power('x', 'y')).get()
    
  1118.     >>> vector.power
    
  1119.     0.25
    
  1120. 
    
  1121. ``Radians``
    
  1122. -----------
    
  1123. 
    
  1124. .. class:: Radians(expression, **extra)
    
  1125. 
    
  1126. Converts a numeric field or expression from degrees to radians.
    
  1127. 
    
  1128. Usage example::
    
  1129. 
    
  1130.     >>> from django.db.models.functions import Radians
    
  1131.     >>> Vector.objects.create(x=-90, y=180)
    
  1132.     >>> vector = Vector.objects.annotate(x_r=Radians('x'), y_r=Radians('y')).get()
    
  1133.     >>> vector.x_r, vector.y_r
    
  1134.     (-1.5707963267948966, 3.141592653589793)
    
  1135. 
    
  1136. It can also be registered as a transform. For example::
    
  1137. 
    
  1138.     >>> from django.db.models import FloatField
    
  1139.     >>> from django.db.models.functions import Radians
    
  1140.     >>> FloatField.register_lookup(Radians)
    
  1141.     >>> # Get vectors whose radians are less than 1
    
  1142.     >>> vectors = Vector.objects.filter(x__radians__lt=1, y__radians__lt=1)
    
  1143. 
    
  1144. ``Random``
    
  1145. ----------
    
  1146. 
    
  1147. .. class:: Random(**extra)
    
  1148. 
    
  1149. Returns a random value in the range ``0.0 ≤ x < 1.0``.
    
  1150. 
    
  1151. ``Round``
    
  1152. ---------
    
  1153. 
    
  1154. .. class:: Round(expression, precision=0, **extra)
    
  1155. 
    
  1156. Rounds a numeric field or expression to ``precision`` (must be an integer)
    
  1157. decimal places. By default, it rounds to the nearest integer. Whether half
    
  1158. values are rounded up or down depends on the database.
    
  1159. 
    
  1160. Usage example::
    
  1161. 
    
  1162.     >>> from django.db.models.functions import Round
    
  1163.     >>> Vector.objects.create(x=5.4, y=-2.37)
    
  1164.     >>> vector = Vector.objects.annotate(x_r=Round('x'), y_r=Round('y', precision=1)).get()
    
  1165.     >>> vector.x_r, vector.y_r
    
  1166.     (5.0, -2.4)
    
  1167. 
    
  1168. It can also be registered as a transform. For example::
    
  1169. 
    
  1170.     >>> from django.db.models import FloatField
    
  1171.     >>> from django.db.models.functions import Round
    
  1172.     >>> FloatField.register_lookup(Round)
    
  1173.     >>> # Get vectors whose round() is less than 20
    
  1174.     >>> vectors = Vector.objects.filter(x__round__lt=20, y__round__lt=20)
    
  1175. 
    
  1176. .. versionchanged:: 4.0
    
  1177. 
    
  1178.     The ``precision`` argument was added.
    
  1179. 
    
  1180. ``Sign``
    
  1181. --------
    
  1182. 
    
  1183. .. class:: Sign(expression, **extra)
    
  1184. 
    
  1185. Returns the sign (-1, 0, 1) of a numeric field or expression.
    
  1186. 
    
  1187. Usage example::
    
  1188. 
    
  1189.     >>> from django.db.models.functions import Sign
    
  1190.     >>> Vector.objects.create(x=5.4, y=-2.3)
    
  1191.     >>> vector = Vector.objects.annotate(x_sign=Sign('x'), y_sign=Sign('y')).get()
    
  1192.     >>> vector.x_sign, vector.y_sign
    
  1193.     (1, -1)
    
  1194. 
    
  1195. It can also be registered as a transform. For example::
    
  1196. 
    
  1197.     >>> from django.db.models import FloatField
    
  1198.     >>> from django.db.models.functions import Sign
    
  1199.     >>> FloatField.register_lookup(Sign)
    
  1200.     >>> # Get vectors whose signs of components are less than 0.
    
  1201.     >>> vectors = Vector.objects.filter(x__sign__lt=0, y__sign__lt=0)
    
  1202. 
    
  1203. ``Sin``
    
  1204. -------
    
  1205. 
    
  1206. .. class:: Sin(expression, **extra)
    
  1207. 
    
  1208. Returns the sine of a numeric field or expression.
    
  1209. 
    
  1210. Usage example::
    
  1211. 
    
  1212.     >>> from django.db.models.functions import Sin
    
  1213.     >>> Vector.objects.create(x=5.4, y=-2.3)
    
  1214.     >>> vector = Vector.objects.annotate(x_sin=Sin('x'), y_sin=Sin('y')).get()
    
  1215.     >>> vector.x_sin, vector.y_sin
    
  1216.     (-0.7727644875559871, -0.7457052121767203)
    
  1217. 
    
  1218. It can also be registered as a transform. For example::
    
  1219. 
    
  1220.     >>> from django.db.models import FloatField
    
  1221.     >>> from django.db.models.functions import Sin
    
  1222.     >>> FloatField.register_lookup(Sin)
    
  1223.     >>> # Get vectors whose sin() is less than 0
    
  1224.     >>> vectors = Vector.objects.filter(x__sin__lt=0, y__sin__lt=0)
    
  1225. 
    
  1226. ``Sqrt``
    
  1227. --------
    
  1228. 
    
  1229. .. class:: Sqrt(expression, **extra)
    
  1230. 
    
  1231. Returns the square root of a nonnegative numeric field or expression.
    
  1232. 
    
  1233. Usage example::
    
  1234. 
    
  1235.     >>> from django.db.models.functions import Sqrt
    
  1236.     >>> Vector.objects.create(x=4.0, y=12.0)
    
  1237.     >>> vector = Vector.objects.annotate(x_sqrt=Sqrt('x'), y_sqrt=Sqrt('y')).get()
    
  1238.     >>> vector.x_sqrt, vector.y_sqrt
    
  1239.     (2.0, 3.46410)
    
  1240. 
    
  1241. It can also be registered as a transform. For example::
    
  1242. 
    
  1243.     >>> from django.db.models import FloatField
    
  1244.     >>> from django.db.models.functions import Sqrt
    
  1245.     >>> FloatField.register_lookup(Sqrt)
    
  1246.     >>> # Get vectors whose sqrt() is less than 5
    
  1247.     >>> vectors = Vector.objects.filter(x__sqrt__lt=5, y__sqrt__lt=5)
    
  1248. 
    
  1249. ``Tan``
    
  1250. -------
    
  1251. 
    
  1252. .. class:: Tan(expression, **extra)
    
  1253. 
    
  1254. Returns the tangent of a numeric field or expression.
    
  1255. 
    
  1256. Usage example::
    
  1257. 
    
  1258.     >>> from django.db.models.functions import Tan
    
  1259.     >>> Vector.objects.create(x=0, y=12)
    
  1260.     >>> vector = Vector.objects.annotate(x_tan=Tan('x'), y_tan=Tan('y')).get()
    
  1261.     >>> vector.x_tan, vector.y_tan
    
  1262.     (0.0, -0.6358599286615808)
    
  1263. 
    
  1264. It can also be registered as a transform. For example::
    
  1265. 
    
  1266.     >>> from django.db.models import FloatField
    
  1267.     >>> from django.db.models.functions import Tan
    
  1268.     >>> FloatField.register_lookup(Tan)
    
  1269.     >>> # Get vectors whose tangent is less than 0
    
  1270.     >>> vectors = Vector.objects.filter(x__tan__lt=0, y__tan__lt=0)
    
  1271. 
    
  1272. .. _text-functions:
    
  1273. 
    
  1274. Text functions
    
  1275. ==============
    
  1276. 
    
  1277. ``Chr``
    
  1278. -------
    
  1279. 
    
  1280. .. class:: Chr(expression, **extra)
    
  1281. 
    
  1282. Accepts a numeric field or expression and returns the text representation of
    
  1283. the expression as a single character. It works the same as Python's :func:`chr`
    
  1284. function.
    
  1285. 
    
  1286. Like :class:`Length`, it can be registered as a transform on ``IntegerField``.
    
  1287. The default lookup name is ``chr``.
    
  1288. 
    
  1289. Usage example::
    
  1290. 
    
  1291.     >>> from django.db.models.functions import Chr
    
  1292.     >>> Author.objects.create(name='Margaret Smith')
    
  1293.     >>> author = Author.objects.filter(name__startswith=Chr(ord('M'))).get()
    
  1294.     >>> print(author.name)
    
  1295.     Margaret Smith
    
  1296. 
    
  1297. ``Concat``
    
  1298. ----------
    
  1299. 
    
  1300. .. class:: Concat(*expressions, **extra)
    
  1301. 
    
  1302. Accepts a list of at least two text fields or expressions and returns the
    
  1303. concatenated text. Each argument must be of a text or char type. If you want
    
  1304. to concatenate a ``TextField()`` with a ``CharField()``, then be sure to tell
    
  1305. Django that the ``output_field`` should be a ``TextField()``. Specifying an
    
  1306. ``output_field`` is also required when concatenating a ``Value`` as in the
    
  1307. example below.
    
  1308. 
    
  1309. This function will never have a null result. On backends where a null argument
    
  1310. results in the entire expression being null, Django will ensure that each null
    
  1311. part is converted to an empty string first.
    
  1312. 
    
  1313. Usage example::
    
  1314. 
    
  1315.     >>> # Get the display name as "name (goes_by)"
    
  1316.     >>> from django.db.models import CharField, Value as V
    
  1317.     >>> from django.db.models.functions import Concat
    
  1318.     >>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')
    
  1319.     >>> author = Author.objects.annotate(
    
  1320.     ...     screen_name=Concat(
    
  1321.     ...         'name', V(' ('), 'goes_by', V(')'),
    
  1322.     ...         output_field=CharField()
    
  1323.     ...     )
    
  1324.     ... ).get()
    
  1325.     >>> print(author.screen_name)
    
  1326.     Margaret Smith (Maggie)
    
  1327. 
    
  1328. ``Left``
    
  1329. --------
    
  1330. 
    
  1331. .. class:: Left(expression, length, **extra)
    
  1332. 
    
  1333. Returns the first ``length`` characters of the given text field or expression.
    
  1334. 
    
  1335. Usage example::
    
  1336. 
    
  1337.     >>> from django.db.models.functions import Left
    
  1338.     >>> Author.objects.create(name='Margaret Smith')
    
  1339.     >>> author = Author.objects.annotate(first_initial=Left('name', 1)).get()
    
  1340.     >>> print(author.first_initial)
    
  1341.     M
    
  1342. 
    
  1343. ``Length``
    
  1344. ----------
    
  1345. 
    
  1346. .. class:: Length(expression, **extra)
    
  1347. 
    
  1348. Accepts a single text field or expression and returns the number of characters
    
  1349. the value has. If the expression is null, then the length will also be null.
    
  1350. 
    
  1351. Usage example::
    
  1352. 
    
  1353.     >>> # Get the length of the name and goes_by fields
    
  1354.     >>> from django.db.models.functions import Length
    
  1355.     >>> Author.objects.create(name='Margaret Smith')
    
  1356.     >>> author = Author.objects.annotate(
    
  1357.     ...    name_length=Length('name'),
    
  1358.     ...    goes_by_length=Length('goes_by')).get()
    
  1359.     >>> print(author.name_length, author.goes_by_length)
    
  1360.     (14, None)
    
  1361. 
    
  1362. It can also be registered as a transform. For example::
    
  1363. 
    
  1364.     >>> from django.db.models import CharField
    
  1365.     >>> from django.db.models.functions import Length
    
  1366.     >>> CharField.register_lookup(Length)
    
  1367.     >>> # Get authors whose name is longer than 7 characters
    
  1368.     >>> authors = Author.objects.filter(name__length__gt=7)
    
  1369. 
    
  1370. ``Lower``
    
  1371. ---------
    
  1372. 
    
  1373. .. class:: Lower(expression, **extra)
    
  1374. 
    
  1375. Accepts a single text field or expression and returns the lowercase
    
  1376. representation.
    
  1377. 
    
  1378. It can also be registered as a transform as described in :class:`Length`.
    
  1379. 
    
  1380. Usage example::
    
  1381. 
    
  1382.     >>> from django.db.models.functions import Lower
    
  1383.     >>> Author.objects.create(name='Margaret Smith')
    
  1384.     >>> author = Author.objects.annotate(name_lower=Lower('name')).get()
    
  1385.     >>> print(author.name_lower)
    
  1386.     margaret smith
    
  1387. 
    
  1388. ``LPad``
    
  1389. --------
    
  1390. 
    
  1391. .. class:: LPad(expression, length, fill_text=Value(' '), **extra)
    
  1392. 
    
  1393. Returns the value of the given text field or expression padded on the left side
    
  1394. with ``fill_text`` so that the resulting value is ``length`` characters long.
    
  1395. The default ``fill_text`` is a space.
    
  1396. 
    
  1397. Usage example::
    
  1398. 
    
  1399.     >>> from django.db.models import Value
    
  1400.     >>> from django.db.models.functions import LPad
    
  1401.     >>> Author.objects.create(name='John', alias='j')
    
  1402.     >>> Author.objects.update(name=LPad('name', 8, Value('abc')))
    
  1403.     1
    
  1404.     >>> print(Author.objects.get(alias='j').name)
    
  1405.     abcaJohn
    
  1406. 
    
  1407. ``LTrim``
    
  1408. ---------
    
  1409. 
    
  1410. .. class:: LTrim(expression, **extra)
    
  1411. 
    
  1412. Similar to :class:`~django.db.models.functions.Trim`, but removes only leading
    
  1413. spaces.
    
  1414. 
    
  1415. ``MD5``
    
  1416. -------
    
  1417. 
    
  1418. .. class:: MD5(expression, **extra)
    
  1419. 
    
  1420. Accepts a single text field or expression and returns the MD5 hash of the
    
  1421. string.
    
  1422. 
    
  1423. It can also be registered as a transform as described in :class:`Length`.
    
  1424. 
    
  1425. Usage example::
    
  1426. 
    
  1427.     >>> from django.db.models.functions import MD5
    
  1428.     >>> Author.objects.create(name='Margaret Smith')
    
  1429.     >>> author = Author.objects.annotate(name_md5=MD5('name')).get()
    
  1430.     >>> print(author.name_md5)
    
  1431.     749fb689816b2db85f5b169c2055b247
    
  1432. 
    
  1433. ``Ord``
    
  1434. -------
    
  1435. 
    
  1436. .. class:: Ord(expression, **extra)
    
  1437. 
    
  1438. Accepts a single text field or expression and returns the Unicode code point
    
  1439. value for the first character of that expression. It works similar to Python's
    
  1440. :func:`ord` function, but an exception isn't raised if the expression is more
    
  1441. than one character long.
    
  1442. 
    
  1443. It can also be registered as a transform as described in :class:`Length`.
    
  1444. The default lookup name is ``ord``.
    
  1445. 
    
  1446. Usage example::
    
  1447. 
    
  1448.     >>> from django.db.models.functions import Ord
    
  1449.     >>> Author.objects.create(name='Margaret Smith')
    
  1450.     >>> author = Author.objects.annotate(name_code_point=Ord('name')).get()
    
  1451.     >>> print(author.name_code_point)
    
  1452.     77
    
  1453. 
    
  1454. ``Repeat``
    
  1455. ----------
    
  1456. 
    
  1457. .. class:: Repeat(expression, number, **extra)
    
  1458. 
    
  1459. Returns the value of the given text field or expression repeated ``number``
    
  1460. times.
    
  1461. 
    
  1462. Usage example::
    
  1463. 
    
  1464.     >>> from django.db.models.functions import Repeat
    
  1465.     >>> Author.objects.create(name='John', alias='j')
    
  1466.     >>> Author.objects.update(name=Repeat('name', 3))
    
  1467.     1
    
  1468.     >>> print(Author.objects.get(alias='j').name)
    
  1469.     JohnJohnJohn
    
  1470. 
    
  1471. ``Replace``
    
  1472. -----------
    
  1473. 
    
  1474. .. class:: Replace(expression, text, replacement=Value(''), **extra)
    
  1475. 
    
  1476. Replaces all occurrences of ``text`` with ``replacement`` in ``expression``.
    
  1477. The default replacement text is the empty string. The arguments to the function
    
  1478. are case-sensitive.
    
  1479. 
    
  1480. Usage example::
    
  1481. 
    
  1482.     >>> from django.db.models import Value
    
  1483.     >>> from django.db.models.functions import Replace
    
  1484.     >>> Author.objects.create(name='Margaret Johnson')
    
  1485.     >>> Author.objects.create(name='Margaret Smith')
    
  1486.     >>> Author.objects.update(name=Replace('name', Value('Margaret'), Value('Margareth')))
    
  1487.     2
    
  1488.     >>> Author.objects.values('name')
    
  1489.     <QuerySet [{'name': 'Margareth Johnson'}, {'name': 'Margareth Smith'}]>
    
  1490. 
    
  1491. ``Reverse``
    
  1492. -----------
    
  1493. 
    
  1494. .. class:: Reverse(expression, **extra)
    
  1495. 
    
  1496. Accepts a single text field or expression and returns the characters of that
    
  1497. expression in reverse order.
    
  1498. 
    
  1499. It can also be registered as a transform as described in :class:`Length`. The
    
  1500. default lookup name is ``reverse``.
    
  1501. 
    
  1502. Usage example::
    
  1503. 
    
  1504.     >>> from django.db.models.functions import Reverse
    
  1505.     >>> Author.objects.create(name='Margaret Smith')
    
  1506.     >>> author = Author.objects.annotate(backward=Reverse('name')).get()
    
  1507.     >>> print(author.backward)
    
  1508.     htimS teragraM
    
  1509. 
    
  1510. ``Right``
    
  1511. ---------
    
  1512. 
    
  1513. .. class:: Right(expression, length, **extra)
    
  1514. 
    
  1515. Returns the last ``length`` characters of the given text field or expression.
    
  1516. 
    
  1517. Usage example::
    
  1518. 
    
  1519.     >>> from django.db.models.functions import Right
    
  1520.     >>> Author.objects.create(name='Margaret Smith')
    
  1521.     >>> author = Author.objects.annotate(last_letter=Right('name', 1)).get()
    
  1522.     >>> print(author.last_letter)
    
  1523.     h
    
  1524. 
    
  1525. ``RPad``
    
  1526. --------
    
  1527. 
    
  1528. .. class:: RPad(expression, length, fill_text=Value(' '), **extra)
    
  1529. 
    
  1530. Similar to :class:`~django.db.models.functions.LPad`, but pads on the right
    
  1531. side.
    
  1532. 
    
  1533. ``RTrim``
    
  1534. ---------
    
  1535. 
    
  1536. .. class:: RTrim(expression, **extra)
    
  1537. 
    
  1538. Similar to :class:`~django.db.models.functions.Trim`, but removes only trailing
    
  1539. spaces.
    
  1540. 
    
  1541. ``SHA1``, ``SHA224``, ``SHA256``, ``SHA384``, and ``SHA512``
    
  1542. ------------------------------------------------------------
    
  1543. 
    
  1544. .. class:: SHA1(expression, **extra)
    
  1545. .. class:: SHA224(expression, **extra)
    
  1546. .. class:: SHA256(expression, **extra)
    
  1547. .. class:: SHA384(expression, **extra)
    
  1548. .. class:: SHA512(expression, **extra)
    
  1549. 
    
  1550. Accepts a single text field or expression and returns the particular hash of
    
  1551. the string.
    
  1552. 
    
  1553. They can also be registered as transforms as described in :class:`Length`.
    
  1554. 
    
  1555. Usage example::
    
  1556. 
    
  1557.     >>> from django.db.models.functions import SHA1
    
  1558.     >>> Author.objects.create(name='Margaret Smith')
    
  1559.     >>> author = Author.objects.annotate(name_sha1=SHA1('name')).get()
    
  1560.     >>> print(author.name_sha1)
    
  1561.     b87efd8a6c991c390be5a68e8a7945a7851c7e5c
    
  1562. 
    
  1563. .. admonition:: PostgreSQL
    
  1564. 
    
  1565.     The `pgcrypto extension <https://www.postgresql.org/docs/current/
    
  1566.     pgcrypto.html>`_ must be installed. You can use the
    
  1567.     :class:`~django.contrib.postgres.operations.CryptoExtension` migration
    
  1568.     operation to install it.
    
  1569. 
    
  1570. .. admonition:: Oracle
    
  1571. 
    
  1572.     Oracle doesn't support the ``SHA224`` function.
    
  1573. 
    
  1574. ``StrIndex``
    
  1575. ------------
    
  1576. 
    
  1577. .. class:: StrIndex(string, substring, **extra)
    
  1578. 
    
  1579. Returns a positive integer corresponding to the 1-indexed position of the first
    
  1580. occurrence of ``substring`` inside ``string``, or 0 if ``substring`` is not
    
  1581. found.
    
  1582. 
    
  1583. Usage example::
    
  1584. 
    
  1585.     >>> from django.db.models import Value as V
    
  1586.     >>> from django.db.models.functions import StrIndex
    
  1587.     >>> Author.objects.create(name='Margaret Smith')
    
  1588.     >>> Author.objects.create(name='Smith, Margaret')
    
  1589.     >>> Author.objects.create(name='Margaret Jackson')
    
  1590.     >>> Author.objects.filter(name='Margaret Jackson').annotate(
    
  1591.     ...     smith_index=StrIndex('name', V('Smith'))
    
  1592.     ... ).get().smith_index
    
  1593.     0
    
  1594.     >>> authors = Author.objects.annotate(
    
  1595.     ...    smith_index=StrIndex('name', V('Smith'))
    
  1596.     ... ).filter(smith_index__gt=0)
    
  1597.     <QuerySet [<Author: Margaret Smith>, <Author: Smith, Margaret>]>
    
  1598. 
    
  1599. .. warning::
    
  1600. 
    
  1601.     In MySQL, a database table's :ref:`collation<mysql-collation>` determines
    
  1602.     whether string comparisons (such as the ``expression`` and ``substring`` of
    
  1603.     this function) are case-sensitive. Comparisons are case-insensitive by
    
  1604.     default.
    
  1605. 
    
  1606. ``Substr``
    
  1607. ----------
    
  1608. 
    
  1609. .. class:: Substr(expression, pos, length=None, **extra)
    
  1610. 
    
  1611. Returns a substring of length ``length`` from the field or expression starting
    
  1612. at position ``pos``. The position is 1-indexed, so the position must be greater
    
  1613. than 0. If ``length`` is ``None``, then the rest of the string will be returned.
    
  1614. 
    
  1615. Usage example::
    
  1616. 
    
  1617.     >>> # Set the alias to the first 5 characters of the name as lowercase
    
  1618.     >>> from django.db.models.functions import Lower, Substr
    
  1619.     >>> Author.objects.create(name='Margaret Smith')
    
  1620.     >>> Author.objects.update(alias=Lower(Substr('name', 1, 5)))
    
  1621.     1
    
  1622.     >>> print(Author.objects.get(name='Margaret Smith').alias)
    
  1623.     marga
    
  1624. 
    
  1625. ``Trim``
    
  1626. --------
    
  1627. 
    
  1628. .. class:: Trim(expression, **extra)
    
  1629. 
    
  1630. Returns the value of the given text field or expression with leading and
    
  1631. trailing spaces removed.
    
  1632. 
    
  1633. Usage example::
    
  1634. 
    
  1635.     >>> from django.db.models.functions import Trim
    
  1636.     >>> Author.objects.create(name='  John  ', alias='j')
    
  1637.     >>> Author.objects.update(name=Trim('name'))
    
  1638.     1
    
  1639.     >>> print(Author.objects.get(alias='j').name)
    
  1640.     John
    
  1641. 
    
  1642. ``Upper``
    
  1643. ---------
    
  1644. 
    
  1645. .. class:: Upper(expression, **extra)
    
  1646. 
    
  1647. Accepts a single text field or expression and returns the uppercase
    
  1648. representation.
    
  1649. 
    
  1650. It can also be registered as a transform as described in :class:`Length`.
    
  1651. 
    
  1652. Usage example::
    
  1653. 
    
  1654.     >>> from django.db.models.functions import Upper
    
  1655.     >>> Author.objects.create(name='Margaret Smith')
    
  1656.     >>> author = Author.objects.annotate(name_upper=Upper('name')).get()
    
  1657.     >>> print(author.name_upper)
    
  1658.     MARGARET SMITH
    
  1659. 
    
  1660. .. _window-functions:
    
  1661. 
    
  1662. Window functions
    
  1663. ================
    
  1664. 
    
  1665. There are a number of functions to use in a
    
  1666. :class:`~django.db.models.expressions.Window` expression for computing the rank
    
  1667. of elements or the :class:`Ntile` of some rows.
    
  1668. 
    
  1669. ``CumeDist``
    
  1670. ------------
    
  1671. 
    
  1672. .. class:: CumeDist(*expressions, **extra)
    
  1673. 
    
  1674. Calculates the cumulative distribution of a value within a window or partition.
    
  1675. The cumulative distribution is defined as the number of rows preceding or
    
  1676. peered with the current row divided by the total number of rows in the frame.
    
  1677. 
    
  1678. ``DenseRank``
    
  1679. -------------
    
  1680. 
    
  1681. .. class:: DenseRank(*expressions, **extra)
    
  1682. 
    
  1683. Equivalent to :class:`Rank` but does not have gaps.
    
  1684. 
    
  1685. ``FirstValue``
    
  1686. --------------
    
  1687. 
    
  1688. .. class:: FirstValue(expression, **extra)
    
  1689. 
    
  1690. Returns the value evaluated at the row that's the first row of the window
    
  1691. frame, or ``None`` if no such value exists.
    
  1692. 
    
  1693. ``Lag``
    
  1694. -------
    
  1695. 
    
  1696. .. class:: Lag(expression, offset=1, default=None, **extra)
    
  1697. 
    
  1698. Calculates the value offset by ``offset``, and if no row exists there, returns
    
  1699. ``default``.
    
  1700. 
    
  1701. ``default`` must have the same type as the ``expression``, however, this is
    
  1702. only validated by the database and not in Python.
    
  1703. 
    
  1704. .. admonition:: MariaDB and ``default``
    
  1705. 
    
  1706.     MariaDB `doesn't support <https://jira.mariadb.org/browse/MDEV-12981>`_
    
  1707.     the ``default`` parameter.
    
  1708. 
    
  1709. ``LastValue``
    
  1710. -------------
    
  1711. 
    
  1712. .. class:: LastValue(expression, **extra)
    
  1713. 
    
  1714. Comparable to :class:`FirstValue`, it calculates the last value in a given
    
  1715. frame clause.
    
  1716. 
    
  1717. ``Lead``
    
  1718. --------
    
  1719. 
    
  1720. .. class:: Lead(expression, offset=1, default=None, **extra)
    
  1721. 
    
  1722. Calculates the leading value in a given :ref:`frame <window-frames>`. Both
    
  1723. ``offset`` and ``default`` are evaluated with respect to the current row.
    
  1724. 
    
  1725. ``default`` must have the same type as the ``expression``, however, this is
    
  1726. only validated by the database and not in Python.
    
  1727. 
    
  1728. .. admonition:: MariaDB and ``default``
    
  1729. 
    
  1730.     MariaDB `doesn't support <https://jira.mariadb.org/browse/MDEV-12981>`_
    
  1731.     the ``default`` parameter.
    
  1732. 
    
  1733. ``NthValue``
    
  1734. ------------
    
  1735. 
    
  1736. .. class:: NthValue(expression, nth=1, **extra)
    
  1737. 
    
  1738. Computes the row relative to the offset ``nth`` (must be a positive value)
    
  1739. within the window. Returns ``None`` if no row exists.
    
  1740. 
    
  1741. Some databases may handle a nonexistent nth-value differently. For example,
    
  1742. Oracle returns an empty string rather than ``None`` for character-based
    
  1743. expressions. Django doesn't do any conversions in these cases.
    
  1744. 
    
  1745. ``Ntile``
    
  1746. ---------
    
  1747. 
    
  1748. .. class:: Ntile(num_buckets=1, **extra)
    
  1749. 
    
  1750. Calculates a partition for each of the rows in the frame clause, distributing
    
  1751. numbers as evenly as possible between 1 and ``num_buckets``. If the rows don't
    
  1752. divide evenly into a number of buckets, one or more buckets will be represented
    
  1753. more frequently.
    
  1754. 
    
  1755. ``PercentRank``
    
  1756. ---------------
    
  1757. 
    
  1758. .. class:: PercentRank(*expressions, **extra)
    
  1759. 
    
  1760. Computes the percentile rank of the rows in the frame clause. This
    
  1761. computation is equivalent to evaluating::
    
  1762. 
    
  1763.     (rank - 1) / (total rows - 1)
    
  1764. 
    
  1765. The following table explains the calculation for the percentile rank of a row:
    
  1766. 
    
  1767. ===== ===== ==== ============ ============
    
  1768. Row # Value Rank Calculation  Percent Rank
    
  1769. ===== ===== ==== ============ ============
    
  1770. 1     15    1    (1-1)/(7-1)  0.0000
    
  1771. 2     20    2    (2-1)/(7-1)  0.1666
    
  1772. 3     20    2    (2-1)/(7-1)  0.1666
    
  1773. 4     20    2    (2-1)/(7-1)  0.1666
    
  1774. 5     30    5    (5-1)/(7-1)  0.6666
    
  1775. 6     30    5    (5-1)/(7-1)  0.6666
    
  1776. 7     40    7    (7-1)/(7-1)  1.0000
    
  1777. ===== ===== ==== ============ ============
    
  1778. 
    
  1779. ``Rank``
    
  1780. --------
    
  1781. 
    
  1782. .. class:: Rank(*expressions, **extra)
    
  1783. 
    
  1784. Comparable to ``RowNumber``, this function ranks rows in the window. The
    
  1785. computed rank contains gaps. Use :class:`DenseRank` to compute rank without
    
  1786. gaps.
    
  1787. 
    
  1788. ``RowNumber``
    
  1789. -------------
    
  1790. 
    
  1791. .. class:: RowNumber(*expressions, **extra)
    
  1792. 
    
  1793. Computes the row number according to the ordering of either the frame clause
    
  1794. or the ordering of the whole query if there is no partitioning of the
    
  1795. :ref:`window frame <window-frames>`.