database-functions.txt 60 KB

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