database-functions.txt 60 KB

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