database-functions.txt 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989
  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. ``JSONObject``
  647. --------------
  648. .. class:: JSONObject(**fields)
  649. Takes a list of key-value pairs and returns a JSON object containing those
  650. pairs.
  651. Usage example:
  652. .. code-block:: pycon
  653. >>> from django.db.models import F
  654. >>> from django.db.models.functions import JSONObject, Lower
  655. >>> Author.objects.create(name="Margaret Smith", alias="msmith", age=25)
  656. >>> author = Author.objects.annotate(
  657. ... json_object=JSONObject(
  658. ... name=Lower("name"),
  659. ... alias="alias",
  660. ... age=F("age") * 2,
  661. ... )
  662. ... ).get()
  663. >>> author.json_object
  664. {'name': 'margaret smith', 'alias': 'msmith', 'age': 50}
  665. .. _math-functions:
  666. Math Functions
  667. ==============
  668. We'll be using the following model in math function examples::
  669. class Vector(models.Model):
  670. x = models.FloatField()
  671. y = models.FloatField()
  672. ``Abs``
  673. -------
  674. .. class:: Abs(expression, **extra)
  675. Returns the absolute value of a numeric field or expression.
  676. Usage example:
  677. .. code-block:: pycon
  678. >>> from django.db.models.functions import Abs
  679. >>> Vector.objects.create(x=-0.5, y=1.1)
  680. >>> vector = Vector.objects.annotate(x_abs=Abs("x"), y_abs=Abs("y")).get()
  681. >>> vector.x_abs, vector.y_abs
  682. (0.5, 1.1)
  683. It can also be registered as a transform. For example:
  684. .. code-block:: pycon
  685. >>> from django.db.models import FloatField
  686. >>> from django.db.models.functions import Abs
  687. >>> FloatField.register_lookup(Abs)
  688. >>> # Get vectors inside the unit cube
  689. >>> vectors = Vector.objects.filter(x__abs__lt=1, y__abs__lt=1)
  690. ``ACos``
  691. --------
  692. .. class:: ACos(expression, **extra)
  693. Returns the arccosine of a numeric field or expression. The expression value
  694. must be within the range -1 to 1.
  695. Usage example:
  696. .. code-block:: pycon
  697. >>> from django.db.models.functions import ACos
  698. >>> Vector.objects.create(x=0.5, y=-0.9)
  699. >>> vector = Vector.objects.annotate(x_acos=ACos("x"), y_acos=ACos("y")).get()
  700. >>> vector.x_acos, vector.y_acos
  701. (1.0471975511965979, 2.6905658417935308)
  702. It can also be registered as a transform. For example:
  703. .. code-block:: pycon
  704. >>> from django.db.models import FloatField
  705. >>> from django.db.models.functions import ACos
  706. >>> FloatField.register_lookup(ACos)
  707. >>> # Get vectors whose arccosine is less than 1
  708. >>> vectors = Vector.objects.filter(x__acos__lt=1, y__acos__lt=1)
  709. ``ASin``
  710. --------
  711. .. class:: ASin(expression, **extra)
  712. Returns the arcsine of a numeric field or expression. The expression value must
  713. be in the range -1 to 1.
  714. Usage example:
  715. .. code-block:: pycon
  716. >>> from django.db.models.functions import ASin
  717. >>> Vector.objects.create(x=0, y=1)
  718. >>> vector = Vector.objects.annotate(x_asin=ASin("x"), y_asin=ASin("y")).get()
  719. >>> vector.x_asin, vector.y_asin
  720. (0.0, 1.5707963267948966)
  721. It can also be registered as a transform. For example:
  722. .. code-block:: pycon
  723. >>> from django.db.models import FloatField
  724. >>> from django.db.models.functions import ASin
  725. >>> FloatField.register_lookup(ASin)
  726. >>> # Get vectors whose arcsine is less than 1
  727. >>> vectors = Vector.objects.filter(x__asin__lt=1, y__asin__lt=1)
  728. ``ATan``
  729. --------
  730. .. class:: ATan(expression, **extra)
  731. Returns the arctangent of a numeric field or expression.
  732. Usage example:
  733. .. code-block:: pycon
  734. >>> from django.db.models.functions import ATan
  735. >>> Vector.objects.create(x=3.12, y=6.987)
  736. >>> vector = Vector.objects.annotate(x_atan=ATan("x"), y_atan=ATan("y")).get()
  737. >>> vector.x_atan, vector.y_atan
  738. (1.2606282660069106, 1.428638798133829)
  739. It can also be registered as a transform. For example:
  740. .. code-block:: pycon
  741. >>> from django.db.models import FloatField
  742. >>> from django.db.models.functions import ATan
  743. >>> FloatField.register_lookup(ATan)
  744. >>> # Get vectors whose arctangent is less than 2
  745. >>> vectors = Vector.objects.filter(x__atan__lt=2, y__atan__lt=2)
  746. ``ATan2``
  747. ---------
  748. .. class:: ATan2(expression1, expression2, **extra)
  749. Returns the arctangent of ``expression1 / expression2``.
  750. Usage example:
  751. .. code-block:: pycon
  752. >>> from django.db.models.functions import ATan2
  753. >>> Vector.objects.create(x=2.5, y=1.9)
  754. >>> vector = Vector.objects.annotate(atan2=ATan2("x", "y")).get()
  755. >>> vector.atan2
  756. 0.9209258773829491
  757. ``Ceil``
  758. --------
  759. .. class:: Ceil(expression, **extra)
  760. Returns the smallest integer greater than or equal to a numeric field or
  761. expression.
  762. Usage example:
  763. .. code-block:: pycon
  764. >>> from django.db.models.functions import Ceil
  765. >>> Vector.objects.create(x=3.12, y=7.0)
  766. >>> vector = Vector.objects.annotate(x_ceil=Ceil("x"), y_ceil=Ceil("y")).get()
  767. >>> vector.x_ceil, vector.y_ceil
  768. (4.0, 7.0)
  769. It can also be registered as a transform. For example:
  770. .. code-block:: pycon
  771. >>> from django.db.models import FloatField
  772. >>> from django.db.models.functions import Ceil
  773. >>> FloatField.register_lookup(Ceil)
  774. >>> # Get vectors whose ceil is less than 10
  775. >>> vectors = Vector.objects.filter(x__ceil__lt=10, y__ceil__lt=10)
  776. ``Cos``
  777. -------
  778. .. class:: Cos(expression, **extra)
  779. Returns the cosine of a numeric field or expression.
  780. Usage example:
  781. .. code-block:: pycon
  782. >>> from django.db.models.functions import Cos
  783. >>> Vector.objects.create(x=-8.0, y=3.1415926)
  784. >>> vector = Vector.objects.annotate(x_cos=Cos("x"), y_cos=Cos("y")).get()
  785. >>> vector.x_cos, vector.y_cos
  786. (-0.14550003380861354, -0.9999999999999986)
  787. It can also be registered as a transform. For example:
  788. .. code-block:: pycon
  789. >>> from django.db.models import FloatField
  790. >>> from django.db.models.functions import Cos
  791. >>> FloatField.register_lookup(Cos)
  792. >>> # Get vectors whose cosine is less than 0.5
  793. >>> vectors = Vector.objects.filter(x__cos__lt=0.5, y__cos__lt=0.5)
  794. ``Cot``
  795. -------
  796. .. class:: Cot(expression, **extra)
  797. Returns the cotangent of a numeric field or expression.
  798. Usage example:
  799. .. code-block:: pycon
  800. >>> from django.db.models.functions import Cot
  801. >>> Vector.objects.create(x=12.0, y=1.0)
  802. >>> vector = Vector.objects.annotate(x_cot=Cot("x"), y_cot=Cot("y")).get()
  803. >>> vector.x_cot, vector.y_cot
  804. (-1.5726734063976826, 0.642092615934331)
  805. It can also be registered as a transform. For example:
  806. .. code-block:: pycon
  807. >>> from django.db.models import FloatField
  808. >>> from django.db.models.functions import Cot
  809. >>> FloatField.register_lookup(Cot)
  810. >>> # Get vectors whose cotangent is less than 1
  811. >>> vectors = Vector.objects.filter(x__cot__lt=1, y__cot__lt=1)
  812. ``Degrees``
  813. -----------
  814. .. class:: Degrees(expression, **extra)
  815. Converts a numeric field or expression from radians to degrees.
  816. Usage example:
  817. .. code-block:: pycon
  818. >>> from django.db.models.functions import Degrees
  819. >>> Vector.objects.create(x=-1.57, y=3.14)
  820. >>> vector = Vector.objects.annotate(x_d=Degrees("x"), y_d=Degrees("y")).get()
  821. >>> vector.x_d, vector.y_d
  822. (-89.95437383553924, 179.9087476710785)
  823. It can also be registered as a transform. For example:
  824. .. code-block:: pycon
  825. >>> from django.db.models import FloatField
  826. >>> from django.db.models.functions import Degrees
  827. >>> FloatField.register_lookup(Degrees)
  828. >>> # Get vectors whose degrees are less than 360
  829. >>> vectors = Vector.objects.filter(x__degrees__lt=360, y__degrees__lt=360)
  830. ``Exp``
  831. -------
  832. .. class:: Exp(expression, **extra)
  833. Returns the value of ``e`` (the natural logarithm base) raised to the power of
  834. a numeric field or expression.
  835. Usage example:
  836. .. code-block:: pycon
  837. >>> from django.db.models.functions import Exp
  838. >>> Vector.objects.create(x=5.4, y=-2.0)
  839. >>> vector = Vector.objects.annotate(x_exp=Exp("x"), y_exp=Exp("y")).get()
  840. >>> vector.x_exp, vector.y_exp
  841. (221.40641620418717, 0.1353352832366127)
  842. It can also be registered as a transform. For example:
  843. .. code-block:: pycon
  844. >>> from django.db.models import FloatField
  845. >>> from django.db.models.functions import Exp
  846. >>> FloatField.register_lookup(Exp)
  847. >>> # Get vectors whose exp() is greater than 10
  848. >>> vectors = Vector.objects.filter(x__exp__gt=10, y__exp__gt=10)
  849. ``Floor``
  850. ---------
  851. .. class:: Floor(expression, **extra)
  852. Returns the largest integer value not greater than a numeric field or
  853. expression.
  854. Usage example:
  855. .. code-block:: pycon
  856. >>> from django.db.models.functions import Floor
  857. >>> Vector.objects.create(x=5.4, y=-2.3)
  858. >>> vector = Vector.objects.annotate(x_floor=Floor("x"), y_floor=Floor("y")).get()
  859. >>> vector.x_floor, vector.y_floor
  860. (5.0, -3.0)
  861. It can also be registered as a transform. For example:
  862. .. code-block:: pycon
  863. >>> from django.db.models import FloatField
  864. >>> from django.db.models.functions import Floor
  865. >>> FloatField.register_lookup(Floor)
  866. >>> # Get vectors whose floor() is greater than 10
  867. >>> vectors = Vector.objects.filter(x__floor__gt=10, y__floor__gt=10)
  868. ``Ln``
  869. ------
  870. .. class:: Ln(expression, **extra)
  871. Returns the natural logarithm a numeric field or expression.
  872. Usage example:
  873. .. code-block:: pycon
  874. >>> from django.db.models.functions import Ln
  875. >>> Vector.objects.create(x=5.4, y=233.0)
  876. >>> vector = Vector.objects.annotate(x_ln=Ln("x"), y_ln=Ln("y")).get()
  877. >>> vector.x_ln, vector.y_ln
  878. (1.6863989535702288, 5.4510384535657)
  879. It can also be registered as a transform. For example:
  880. .. code-block:: pycon
  881. >>> from django.db.models import FloatField
  882. >>> from django.db.models.functions import Ln
  883. >>> FloatField.register_lookup(Ln)
  884. >>> # Get vectors whose value greater than e
  885. >>> vectors = Vector.objects.filter(x__ln__gt=1, y__ln__gt=1)
  886. ``Log``
  887. -------
  888. .. class:: Log(expression1, expression2, **extra)
  889. Accepts two numeric fields or expressions and returns the logarithm of
  890. the second to base of the first.
  891. Usage example:
  892. .. code-block:: pycon
  893. >>> from django.db.models.functions import Log
  894. >>> Vector.objects.create(x=2.0, y=4.0)
  895. >>> vector = Vector.objects.annotate(log=Log("x", "y")).get()
  896. >>> vector.log
  897. 2.0
  898. ``Mod``
  899. -------
  900. .. class:: Mod(expression1, expression2, **extra)
  901. Accepts two numeric fields or expressions and returns the remainder of
  902. the first divided by the second (modulo operation).
  903. Usage example:
  904. .. code-block:: pycon
  905. >>> from django.db.models.functions import Mod
  906. >>> Vector.objects.create(x=5.4, y=2.3)
  907. >>> vector = Vector.objects.annotate(mod=Mod("x", "y")).get()
  908. >>> vector.mod
  909. 0.8
  910. ``Pi``
  911. ------
  912. .. class:: Pi(**extra)
  913. Returns the value of the mathematical constant ``π``.
  914. ``Power``
  915. ---------
  916. .. class:: Power(expression1, expression2, **extra)
  917. Accepts two numeric fields or expressions and returns the value of the first
  918. raised to the power of the second.
  919. Usage example:
  920. .. code-block:: pycon
  921. >>> from django.db.models.functions import Power
  922. >>> Vector.objects.create(x=2, y=-2)
  923. >>> vector = Vector.objects.annotate(power=Power("x", "y")).get()
  924. >>> vector.power
  925. 0.25
  926. ``Radians``
  927. -----------
  928. .. class:: Radians(expression, **extra)
  929. Converts a numeric field or expression from degrees to radians.
  930. Usage example:
  931. .. code-block:: pycon
  932. >>> from django.db.models.functions import Radians
  933. >>> Vector.objects.create(x=-90, y=180)
  934. >>> vector = Vector.objects.annotate(x_r=Radians("x"), y_r=Radians("y")).get()
  935. >>> vector.x_r, vector.y_r
  936. (-1.5707963267948966, 3.141592653589793)
  937. It can also be registered as a transform. For example:
  938. .. code-block:: pycon
  939. >>> from django.db.models import FloatField
  940. >>> from django.db.models.functions import Radians
  941. >>> FloatField.register_lookup(Radians)
  942. >>> # Get vectors whose radians are less than 1
  943. >>> vectors = Vector.objects.filter(x__radians__lt=1, y__radians__lt=1)
  944. ``Random``
  945. ----------
  946. .. class:: Random(**extra)
  947. Returns a random value in the range ``0.0 ≤ x < 1.0``.
  948. ``Round``
  949. ---------
  950. .. class:: Round(expression, precision=0, **extra)
  951. Rounds a numeric field or expression to ``precision`` (must be an integer)
  952. decimal places. By default, it rounds to the nearest integer. Whether half
  953. values are rounded up or down depends on the database.
  954. Usage example:
  955. .. code-block:: pycon
  956. >>> from django.db.models.functions import Round
  957. >>> Vector.objects.create(x=5.4, y=-2.37)
  958. >>> vector = Vector.objects.annotate(x_r=Round("x"), y_r=Round("y", precision=1)).get()
  959. >>> vector.x_r, vector.y_r
  960. (5.0, -2.4)
  961. It can also be registered as a transform. For example:
  962. .. code-block:: pycon
  963. >>> from django.db.models import FloatField
  964. >>> from django.db.models.functions import Round
  965. >>> FloatField.register_lookup(Round)
  966. >>> # Get vectors whose round() is less than 20
  967. >>> vectors = Vector.objects.filter(x__round__lt=20, y__round__lt=20)
  968. ``Sign``
  969. --------
  970. .. class:: Sign(expression, **extra)
  971. Returns the sign (-1, 0, 1) of a numeric field or expression.
  972. Usage example:
  973. .. code-block:: pycon
  974. >>> from django.db.models.functions import Sign
  975. >>> Vector.objects.create(x=5.4, y=-2.3)
  976. >>> vector = Vector.objects.annotate(x_sign=Sign("x"), y_sign=Sign("y")).get()
  977. >>> vector.x_sign, vector.y_sign
  978. (1, -1)
  979. It can also be registered as a transform. For example:
  980. .. code-block:: pycon
  981. >>> from django.db.models import FloatField
  982. >>> from django.db.models.functions import Sign
  983. >>> FloatField.register_lookup(Sign)
  984. >>> # Get vectors whose signs of components are less than 0.
  985. >>> vectors = Vector.objects.filter(x__sign__lt=0, y__sign__lt=0)
  986. ``Sin``
  987. -------
  988. .. class:: Sin(expression, **extra)
  989. Returns the sine of a numeric field or expression.
  990. Usage example:
  991. .. code-block:: pycon
  992. >>> from django.db.models.functions import Sin
  993. >>> Vector.objects.create(x=5.4, y=-2.3)
  994. >>> vector = Vector.objects.annotate(x_sin=Sin("x"), y_sin=Sin("y")).get()
  995. >>> vector.x_sin, vector.y_sin
  996. (-0.7727644875559871, -0.7457052121767203)
  997. It can also be registered as a transform. For example:
  998. .. code-block:: pycon
  999. >>> from django.db.models import FloatField
  1000. >>> from django.db.models.functions import Sin
  1001. >>> FloatField.register_lookup(Sin)
  1002. >>> # Get vectors whose sin() is less than 0
  1003. >>> vectors = Vector.objects.filter(x__sin__lt=0, y__sin__lt=0)
  1004. ``Sqrt``
  1005. --------
  1006. .. class:: Sqrt(expression, **extra)
  1007. Returns the square root of a nonnegative numeric field or expression.
  1008. Usage example:
  1009. .. code-block:: pycon
  1010. >>> from django.db.models.functions import Sqrt
  1011. >>> Vector.objects.create(x=4.0, y=12.0)
  1012. >>> vector = Vector.objects.annotate(x_sqrt=Sqrt("x"), y_sqrt=Sqrt("y")).get()
  1013. >>> vector.x_sqrt, vector.y_sqrt
  1014. (2.0, 3.46410)
  1015. It can also be registered as a transform. For example:
  1016. .. code-block:: pycon
  1017. >>> from django.db.models import FloatField
  1018. >>> from django.db.models.functions import Sqrt
  1019. >>> FloatField.register_lookup(Sqrt)
  1020. >>> # Get vectors whose sqrt() is less than 5
  1021. >>> vectors = Vector.objects.filter(x__sqrt__lt=5, y__sqrt__lt=5)
  1022. ``Tan``
  1023. -------
  1024. .. class:: Tan(expression, **extra)
  1025. Returns the tangent of a numeric field or expression.
  1026. Usage example:
  1027. .. code-block:: pycon
  1028. >>> from django.db.models.functions import Tan
  1029. >>> Vector.objects.create(x=0, y=12)
  1030. >>> vector = Vector.objects.annotate(x_tan=Tan("x"), y_tan=Tan("y")).get()
  1031. >>> vector.x_tan, vector.y_tan
  1032. (0.0, -0.6358599286615808)
  1033. It can also be registered as a transform. For example:
  1034. .. code-block:: pycon
  1035. >>> from django.db.models import FloatField
  1036. >>> from django.db.models.functions import Tan
  1037. >>> FloatField.register_lookup(Tan)
  1038. >>> # Get vectors whose tangent is less than 0
  1039. >>> vectors = Vector.objects.filter(x__tan__lt=0, y__tan__lt=0)
  1040. .. _text-functions:
  1041. Text functions
  1042. ==============
  1043. ``Chr``
  1044. -------
  1045. .. class:: Chr(expression, **extra)
  1046. Accepts a numeric field or expression and returns the text representation of
  1047. the expression as a single character. It works the same as Python's :func:`chr`
  1048. function.
  1049. Like :class:`Length`, it can be registered as a transform on ``IntegerField``.
  1050. The default lookup name is ``chr``.
  1051. Usage example:
  1052. .. code-block:: pycon
  1053. >>> from django.db.models.functions import Chr
  1054. >>> Author.objects.create(name="Margaret Smith")
  1055. >>> author = Author.objects.filter(name__startswith=Chr(ord("M"))).get()
  1056. >>> print(author.name)
  1057. Margaret Smith
  1058. ``Concat``
  1059. ----------
  1060. .. class:: Concat(*expressions, **extra)
  1061. Accepts a list of at least two text fields or expressions and returns the
  1062. concatenated text. Each argument must be of a text or char type. If you want
  1063. to concatenate a ``TextField()`` with a ``CharField()``, then be sure to tell
  1064. Django that the ``output_field`` should be a ``TextField()``. Specifying an
  1065. ``output_field`` is also required when concatenating a ``Value`` as in the
  1066. example below.
  1067. This function will never have a null result. On backends where a null argument
  1068. results in the entire expression being null, Django will ensure that each null
  1069. part is converted to an empty string first.
  1070. Usage example:
  1071. .. code-block:: pycon
  1072. >>> # Get the display name as "name (goes_by)"
  1073. >>> from django.db.models import CharField, Value as V
  1074. >>> from django.db.models.functions import Concat
  1075. >>> Author.objects.create(name="Margaret Smith", goes_by="Maggie")
  1076. >>> author = Author.objects.annotate(
  1077. ... screen_name=Concat("name", V(" ("), "goes_by", V(")"), output_field=CharField())
  1078. ... ).get()
  1079. >>> print(author.screen_name)
  1080. Margaret Smith (Maggie)
  1081. ``Left``
  1082. --------
  1083. .. class:: Left(expression, length, **extra)
  1084. Returns the first ``length`` characters of the given text field or expression.
  1085. Usage example:
  1086. .. code-block:: pycon
  1087. >>> from django.db.models.functions import Left
  1088. >>> Author.objects.create(name="Margaret Smith")
  1089. >>> author = Author.objects.annotate(first_initial=Left("name", 1)).get()
  1090. >>> print(author.first_initial)
  1091. M
  1092. ``Length``
  1093. ----------
  1094. .. class:: Length(expression, **extra)
  1095. Accepts a single text field or expression and returns the number of characters
  1096. the value has. If the expression is null, then the length will also be null.
  1097. Usage example:
  1098. .. code-block:: pycon
  1099. >>> # Get the length of the name and goes_by fields
  1100. >>> from django.db.models.functions import Length
  1101. >>> Author.objects.create(name="Margaret Smith")
  1102. >>> author = Author.objects.annotate(
  1103. ... name_length=Length("name"), goes_by_length=Length("goes_by")
  1104. ... ).get()
  1105. >>> print(author.name_length, author.goes_by_length)
  1106. (14, None)
  1107. It can also be registered as a transform. For example:
  1108. .. code-block:: pycon
  1109. >>> from django.db.models import CharField
  1110. >>> from django.db.models.functions import Length
  1111. >>> CharField.register_lookup(Length)
  1112. >>> # Get authors whose name is longer than 7 characters
  1113. >>> authors = Author.objects.filter(name__length__gt=7)
  1114. ``Lower``
  1115. ---------
  1116. .. class:: Lower(expression, **extra)
  1117. Accepts a single text field or expression and returns the lowercase
  1118. representation.
  1119. It can also be registered as a transform as described in :class:`Length`.
  1120. Usage example:
  1121. .. code-block:: pycon
  1122. >>> from django.db.models.functions import Lower
  1123. >>> Author.objects.create(name="Margaret Smith")
  1124. >>> author = Author.objects.annotate(name_lower=Lower("name")).get()
  1125. >>> print(author.name_lower)
  1126. margaret smith
  1127. ``LPad``
  1128. --------
  1129. .. class:: LPad(expression, length, fill_text=Value(' '), **extra)
  1130. Returns the value of the given text field or expression padded on the left side
  1131. with ``fill_text`` so that the resulting value is ``length`` characters long.
  1132. The default ``fill_text`` is a space.
  1133. Usage example:
  1134. .. code-block:: pycon
  1135. >>> from django.db.models import Value
  1136. >>> from django.db.models.functions import LPad
  1137. >>> Author.objects.create(name="John", alias="j")
  1138. >>> Author.objects.update(name=LPad("name", 8, Value("abc")))
  1139. 1
  1140. >>> print(Author.objects.get(alias="j").name)
  1141. abcaJohn
  1142. ``LTrim``
  1143. ---------
  1144. .. class:: LTrim(expression, **extra)
  1145. Similar to :class:`~django.db.models.functions.Trim`, but removes only leading
  1146. spaces.
  1147. ``MD5``
  1148. -------
  1149. .. class:: MD5(expression, **extra)
  1150. Accepts a single text field or expression and returns the MD5 hash of the
  1151. string.
  1152. It can also be registered as a transform as described in :class:`Length`.
  1153. Usage example:
  1154. .. code-block:: pycon
  1155. >>> from django.db.models.functions import MD5
  1156. >>> Author.objects.create(name="Margaret Smith")
  1157. >>> author = Author.objects.annotate(name_md5=MD5("name")).get()
  1158. >>> print(author.name_md5)
  1159. 749fb689816b2db85f5b169c2055b247
  1160. ``Ord``
  1161. -------
  1162. .. class:: Ord(expression, **extra)
  1163. Accepts a single text field or expression and returns the Unicode code point
  1164. value for the first character of that expression. It works similar to Python's
  1165. :func:`ord` function, but an exception isn't raised if the expression is more
  1166. than one character long.
  1167. It can also be registered as a transform as described in :class:`Length`.
  1168. The default lookup name is ``ord``.
  1169. Usage example:
  1170. .. code-block:: pycon
  1171. >>> from django.db.models.functions import Ord
  1172. >>> Author.objects.create(name="Margaret Smith")
  1173. >>> author = Author.objects.annotate(name_code_point=Ord("name")).get()
  1174. >>> print(author.name_code_point)
  1175. 77
  1176. ``Repeat``
  1177. ----------
  1178. .. class:: Repeat(expression, number, **extra)
  1179. Returns the value of the given text field or expression repeated ``number``
  1180. times.
  1181. Usage example:
  1182. .. code-block:: pycon
  1183. >>> from django.db.models.functions import Repeat
  1184. >>> Author.objects.create(name="John", alias="j")
  1185. >>> Author.objects.update(name=Repeat("name", 3))
  1186. 1
  1187. >>> print(Author.objects.get(alias="j").name)
  1188. JohnJohnJohn
  1189. ``Replace``
  1190. -----------
  1191. .. class:: Replace(expression, text, replacement=Value(''), **extra)
  1192. Replaces all occurrences of ``text`` with ``replacement`` in ``expression``.
  1193. The default replacement text is the empty string. The arguments to the function
  1194. are case-sensitive.
  1195. Usage example:
  1196. .. code-block:: pycon
  1197. >>> from django.db.models import Value
  1198. >>> from django.db.models.functions import Replace
  1199. >>> Author.objects.create(name="Margaret Johnson")
  1200. >>> Author.objects.create(name="Margaret Smith")
  1201. >>> Author.objects.update(name=Replace("name", Value("Margaret"), Value("Margareth")))
  1202. 2
  1203. >>> Author.objects.values("name")
  1204. <QuerySet [{'name': 'Margareth Johnson'}, {'name': 'Margareth Smith'}]>
  1205. ``Reverse``
  1206. -----------
  1207. .. class:: Reverse(expression, **extra)
  1208. Accepts a single text field or expression and returns the characters of that
  1209. expression in reverse order.
  1210. It can also be registered as a transform as described in :class:`Length`. The
  1211. default lookup name is ``reverse``.
  1212. Usage example:
  1213. .. code-block:: pycon
  1214. >>> from django.db.models.functions import Reverse
  1215. >>> Author.objects.create(name="Margaret Smith")
  1216. >>> author = Author.objects.annotate(backward=Reverse("name")).get()
  1217. >>> print(author.backward)
  1218. htimS teragraM
  1219. ``Right``
  1220. ---------
  1221. .. class:: Right(expression, length, **extra)
  1222. Returns the last ``length`` characters of the given text field or expression.
  1223. Usage example:
  1224. .. code-block:: pycon
  1225. >>> from django.db.models.functions import Right
  1226. >>> Author.objects.create(name="Margaret Smith")
  1227. >>> author = Author.objects.annotate(last_letter=Right("name", 1)).get()
  1228. >>> print(author.last_letter)
  1229. h
  1230. ``RPad``
  1231. --------
  1232. .. class:: RPad(expression, length, fill_text=Value(' '), **extra)
  1233. Similar to :class:`~django.db.models.functions.LPad`, but pads on the right
  1234. side.
  1235. ``RTrim``
  1236. ---------
  1237. .. class:: RTrim(expression, **extra)
  1238. Similar to :class:`~django.db.models.functions.Trim`, but removes only trailing
  1239. spaces.
  1240. ``SHA1``, ``SHA224``, ``SHA256``, ``SHA384``, and ``SHA512``
  1241. ------------------------------------------------------------
  1242. .. class:: SHA1(expression, **extra)
  1243. .. class:: SHA224(expression, **extra)
  1244. .. class:: SHA256(expression, **extra)
  1245. .. class:: SHA384(expression, **extra)
  1246. .. class:: SHA512(expression, **extra)
  1247. Accepts a single text field or expression and returns the particular hash of
  1248. the string.
  1249. They can also be registered as transforms as described in :class:`Length`.
  1250. Usage example:
  1251. .. code-block:: pycon
  1252. >>> from django.db.models.functions import SHA1
  1253. >>> Author.objects.create(name="Margaret Smith")
  1254. >>> author = Author.objects.annotate(name_sha1=SHA1("name")).get()
  1255. >>> print(author.name_sha1)
  1256. b87efd8a6c991c390be5a68e8a7945a7851c7e5c
  1257. .. admonition:: PostgreSQL
  1258. The `pgcrypto extension <https://www.postgresql.org/docs/current/
  1259. pgcrypto.html>`_ must be installed. You can use the
  1260. :class:`~django.contrib.postgres.operations.CryptoExtension` migration
  1261. operation to install it.
  1262. .. admonition:: Oracle
  1263. Oracle doesn't support the ``SHA224`` function.
  1264. ``StrIndex``
  1265. ------------
  1266. .. class:: StrIndex(string, substring, **extra)
  1267. Returns a positive integer corresponding to the 1-indexed position of the first
  1268. occurrence of ``substring`` inside ``string``, or 0 if ``substring`` is not
  1269. found.
  1270. Usage example:
  1271. .. code-block:: pycon
  1272. >>> from django.db.models import Value as V
  1273. >>> from django.db.models.functions import StrIndex
  1274. >>> Author.objects.create(name="Margaret Smith")
  1275. >>> Author.objects.create(name="Smith, Margaret")
  1276. >>> Author.objects.create(name="Margaret Jackson")
  1277. >>> Author.objects.filter(name="Margaret Jackson").annotate(
  1278. ... smith_index=StrIndex("name", V("Smith"))
  1279. ... ).get().smith_index
  1280. 0
  1281. >>> authors = Author.objects.annotate(smith_index=StrIndex("name", V("Smith"))).filter(
  1282. ... smith_index__gt=0
  1283. ... )
  1284. <QuerySet [<Author: Margaret Smith>, <Author: Smith, Margaret>]>
  1285. .. warning::
  1286. In MySQL, a database table's :ref:`collation<mysql-collation>` determines
  1287. whether string comparisons (such as the ``expression`` and ``substring`` of
  1288. this function) are case-sensitive. Comparisons are case-insensitive by
  1289. default.
  1290. ``Substr``
  1291. ----------
  1292. .. class:: Substr(expression, pos, length=None, **extra)
  1293. Returns a substring of length ``length`` from the field or expression starting
  1294. at position ``pos``. The position is 1-indexed, so the position must be greater
  1295. than 0. If ``length`` is ``None``, then the rest of the string will be returned.
  1296. Usage example:
  1297. .. code-block:: pycon
  1298. >>> # Set the alias to the first 5 characters of the name as lowercase
  1299. >>> from django.db.models.functions import Lower, Substr
  1300. >>> Author.objects.create(name="Margaret Smith")
  1301. >>> Author.objects.update(alias=Lower(Substr("name", 1, 5)))
  1302. 1
  1303. >>> print(Author.objects.get(name="Margaret Smith").alias)
  1304. marga
  1305. ``Trim``
  1306. --------
  1307. .. class:: Trim(expression, **extra)
  1308. Returns the value of the given text field or expression with leading and
  1309. trailing spaces removed.
  1310. Usage example:
  1311. .. code-block:: pycon
  1312. >>> from django.db.models.functions import Trim
  1313. >>> Author.objects.create(name=" John ", alias="j")
  1314. >>> Author.objects.update(name=Trim("name"))
  1315. 1
  1316. >>> print(Author.objects.get(alias="j").name)
  1317. John
  1318. ``Upper``
  1319. ---------
  1320. .. class:: Upper(expression, **extra)
  1321. Accepts a single text field or expression and returns the uppercase
  1322. representation.
  1323. It can also be registered as a transform as described in :class:`Length`.
  1324. Usage example:
  1325. .. code-block:: pycon
  1326. >>> from django.db.models.functions import Upper
  1327. >>> Author.objects.create(name="Margaret Smith")
  1328. >>> author = Author.objects.annotate(name_upper=Upper("name")).get()
  1329. >>> print(author.name_upper)
  1330. MARGARET SMITH
  1331. .. _window-functions:
  1332. Window functions
  1333. ================
  1334. There are a number of functions to use in a
  1335. :class:`~django.db.models.expressions.Window` expression for computing the rank
  1336. of elements or the :class:`Ntile` of some rows.
  1337. ``CumeDist``
  1338. ------------
  1339. .. class:: CumeDist(*expressions, **extra)
  1340. Calculates the cumulative distribution of a value within a window or partition.
  1341. The cumulative distribution is defined as the number of rows preceding or
  1342. peered with the current row divided by the total number of rows in the frame.
  1343. ``DenseRank``
  1344. -------------
  1345. .. class:: DenseRank(*expressions, **extra)
  1346. Equivalent to :class:`Rank` but does not have gaps.
  1347. ``FirstValue``
  1348. --------------
  1349. .. class:: FirstValue(expression, **extra)
  1350. Returns the value evaluated at the row that's the first row of the window
  1351. frame, or ``None`` if no such value exists.
  1352. ``Lag``
  1353. -------
  1354. .. class:: Lag(expression, offset=1, default=None, **extra)
  1355. Calculates the value offset by ``offset``, and if no row exists there, returns
  1356. ``default``.
  1357. ``default`` must have the same type as the ``expression``, however, this is
  1358. only validated by the database and not in Python.
  1359. .. admonition:: MariaDB and ``default``
  1360. MariaDB `doesn't support <https://jira.mariadb.org/browse/MDEV-12981>`_
  1361. the ``default`` parameter.
  1362. ``LastValue``
  1363. -------------
  1364. .. class:: LastValue(expression, **extra)
  1365. Comparable to :class:`FirstValue`, it calculates the last value in a given
  1366. frame clause.
  1367. ``Lead``
  1368. --------
  1369. .. class:: Lead(expression, offset=1, default=None, **extra)
  1370. Calculates the leading value in a given :ref:`frame <window-frames>`. Both
  1371. ``offset`` and ``default`` are evaluated with respect to the current row.
  1372. ``default`` must have the same type as the ``expression``, however, this is
  1373. only validated by the database and not in Python.
  1374. .. admonition:: MariaDB and ``default``
  1375. MariaDB `doesn't support <https://jira.mariadb.org/browse/MDEV-12981>`_
  1376. the ``default`` parameter.
  1377. ``NthValue``
  1378. ------------
  1379. .. class:: NthValue(expression, nth=1, **extra)
  1380. Computes the row relative to the offset ``nth`` (must be a positive value)
  1381. within the window. Returns ``None`` if no row exists.
  1382. Some databases may handle a nonexistent nth-value differently. For example,
  1383. Oracle returns an empty string rather than ``None`` for character-based
  1384. expressions. Django doesn't do any conversions in these cases.
  1385. ``Ntile``
  1386. ---------
  1387. .. class:: Ntile(num_buckets=1, **extra)
  1388. Calculates a partition for each of the rows in the frame clause, distributing
  1389. numbers as evenly as possible between 1 and ``num_buckets``. If the rows don't
  1390. divide evenly into a number of buckets, one or more buckets will be represented
  1391. more frequently.
  1392. ``PercentRank``
  1393. ---------------
  1394. .. class:: PercentRank(*expressions, **extra)
  1395. Computes the relative rank of the rows in the frame clause. This computation is
  1396. equivalent to evaluating:
  1397. .. code-block:: text
  1398. (rank - 1) / (total rows - 1)
  1399. The following table explains the calculation for the relative rank of a row:
  1400. ===== ===== ==== ============ =============
  1401. Row # Value Rank Calculation Relative Rank
  1402. ===== ===== ==== ============ =============
  1403. 1 15 1 (1-1)/(7-1) 0.0000
  1404. 2 20 2 (2-1)/(7-1) 0.1666
  1405. 3 20 2 (2-1)/(7-1) 0.1666
  1406. 4 20 2 (2-1)/(7-1) 0.1666
  1407. 5 30 5 (5-1)/(7-1) 0.6666
  1408. 6 30 5 (5-1)/(7-1) 0.6666
  1409. 7 40 7 (7-1)/(7-1) 1.0000
  1410. ===== ===== ==== ============ =============
  1411. ``Rank``
  1412. --------
  1413. .. class:: Rank(*expressions, **extra)
  1414. Comparable to :class:`RowNumber`, this function ranks rows in the window. The
  1415. computed rank contains gaps. Use :class:`DenseRank` to compute rank without
  1416. gaps.
  1417. ``RowNumber``
  1418. -------------
  1419. .. class:: RowNumber(*expressions, **extra)
  1420. Computes the row number according to the ordering of either the frame clause
  1421. or the ordering of the whole query if there is no partitioning of the
  1422. :ref:`window frame <window-frames>`.