database-functions.txt 60 KB

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