2
0

database-functions.txt 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994
  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. .. versionchanged:: 4.2
  432. Support for microsecond precision on MySQL and millisecond precision on
  433. SQLite were added.
  434. .. versionchanged:: 5.0
  435. In older versions, the SQL ``CURRENT_TIMESTAMP`` was used on Oracle instead
  436. of ``LOCALTIMESTAMP``.
  437. ``Trunc``
  438. ---------
  439. .. class:: Trunc(expression, kind, output_field=None, tzinfo=None, **extra)
  440. Truncates a date up to a significant component.
  441. When you only care if something happened in a particular year, hour, or day,
  442. but not the exact second, then ``Trunc`` (and its subclasses) can be useful to
  443. filter or aggregate your data. For example, you can use ``Trunc`` to calculate
  444. the number of sales per day.
  445. ``Trunc`` takes a single ``expression``, representing a ``DateField``,
  446. ``TimeField``, or ``DateTimeField``, a ``kind`` representing a date or time
  447. part, and an ``output_field`` that's either ``DateTimeField()``,
  448. ``TimeField()``, or ``DateField()``. It returns a datetime, date, or time
  449. depending on ``output_field``, with fields up to ``kind`` set to their minimum
  450. value. If ``output_field`` is omitted, it will default to the ``output_field``
  451. of ``expression``. A ``tzinfo`` subclass, usually provided by :mod:`zoneinfo`,
  452. can be passed to truncate a value in a specific timezone.
  453. Given the datetime ``2015-06-15 14:30:50.000321+00:00``, the built-in ``kind``\s
  454. return:
  455. * "year": 2015-01-01 00:00:00+00:00
  456. * "quarter": 2015-04-01 00:00:00+00:00
  457. * "month": 2015-06-01 00:00:00+00:00
  458. * "week": 2015-06-15 00:00:00+00:00
  459. * "day": 2015-06-15 00:00:00+00:00
  460. * "hour": 2015-06-15 14:00:00+00:00
  461. * "minute": 2015-06-15 14:30:00+00:00
  462. * "second": 2015-06-15 14:30:50+00:00
  463. If a different timezone like ``Australia/Melbourne`` is active in Django, then
  464. the datetime is converted to the new timezone before the value is truncated.
  465. The timezone offset for Melbourne in the example date above is +10:00. The
  466. values returned when this timezone is active will be:
  467. * "year": 2015-01-01 00:00:00+11:00
  468. * "quarter": 2015-04-01 00:00:00+10:00
  469. * "month": 2015-06-01 00:00:00+10:00
  470. * "week": 2015-06-16 00:00:00+10:00
  471. * "day": 2015-06-16 00:00:00+10:00
  472. * "hour": 2015-06-16 00:00:00+10:00
  473. * "minute": 2015-06-16 00:30:00+10:00
  474. * "second": 2015-06-16 00:30:50+10:00
  475. The year has an offset of +11:00 because the result transitioned into daylight
  476. saving time.
  477. Each ``kind`` above has a corresponding ``Trunc`` subclass (listed below) that
  478. should typically be used instead of the more verbose equivalent,
  479. e.g. use ``TruncYear(...)`` rather than ``Trunc(..., kind='year')``.
  480. The subclasses are all defined as transforms, but they aren't registered with
  481. any fields, because the lookup names are already reserved by the ``Extract``
  482. subclasses.
  483. Usage example:
  484. .. code-block:: pycon
  485. >>> from datetime import datetime
  486. >>> from django.db.models import Count, DateTimeField
  487. >>> from django.db.models.functions import Trunc
  488. >>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 30, 50, 321))
  489. >>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 40, 2, 123))
  490. >>> Experiment.objects.create(start_datetime=datetime(2015, 12, 25, 10, 5, 27, 999))
  491. >>> experiments_per_day = (
  492. ... Experiment.objects.annotate(
  493. ... start_day=Trunc("start_datetime", "day", output_field=DateTimeField())
  494. ... )
  495. ... .values("start_day")
  496. ... .annotate(experiments=Count("id"))
  497. ... )
  498. >>> for exp in experiments_per_day:
  499. ... print(exp["start_day"], exp["experiments"])
  500. ...
  501. 2015-06-15 00:00:00 2
  502. 2015-12-25 00:00:00 1
  503. >>> experiments = Experiment.objects.annotate(
  504. ... start_day=Trunc("start_datetime", "day", output_field=DateTimeField())
  505. ... ).filter(start_day=datetime(2015, 6, 15))
  506. >>> for exp in experiments:
  507. ... print(exp.start_datetime)
  508. ...
  509. 2015-06-15 14:30:50.000321
  510. 2015-06-15 14:40:02.000123
  511. ``DateField`` truncation
  512. ~~~~~~~~~~~~~~~~~~~~~~~~
  513. .. class:: TruncYear(expression, output_field=None, tzinfo=None, **extra)
  514. .. attribute:: kind = 'year'
  515. .. class:: TruncMonth(expression, output_field=None, tzinfo=None, **extra)
  516. .. attribute:: kind = 'month'
  517. .. class:: TruncWeek(expression, output_field=None, tzinfo=None, **extra)
  518. Truncates to midnight on the Monday of the week.
  519. .. attribute:: kind = 'week'
  520. .. class:: TruncQuarter(expression, output_field=None, tzinfo=None, **extra)
  521. .. attribute:: kind = 'quarter'
  522. These are logically equivalent to ``Trunc('date_field', kind)``. They truncate
  523. all parts of the date up to ``kind`` which allows grouping or filtering dates
  524. with less precision. ``expression`` can have an ``output_field`` of either
  525. ``DateField`` or ``DateTimeField``.
  526. Since ``DateField``\s don't have a time component, only ``Trunc`` subclasses
  527. that deal with date-parts can be used with ``DateField``:
  528. .. code-block:: pycon
  529. >>> from datetime import datetime, timezone
  530. >>> from django.db.models import Count
  531. >>> from django.db.models.functions import TruncMonth, TruncYear
  532. >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
  533. >>> start2 = datetime(2015, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)
  534. >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)
  535. >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
  536. >>> Experiment.objects.create(start_datetime=start2, start_date=start2.date())
  537. >>> Experiment.objects.create(start_datetime=start3, start_date=start3.date())
  538. >>> experiments_per_year = (
  539. ... Experiment.objects.annotate(year=TruncYear("start_date"))
  540. ... .values("year")
  541. ... .annotate(experiments=Count("id"))
  542. ... )
  543. >>> for exp in experiments_per_year:
  544. ... print(exp["year"], exp["experiments"])
  545. ...
  546. 2014-01-01 1
  547. 2015-01-01 2
  548. >>> import zoneinfo
  549. >>> melb = zoneinfo.ZoneInfo("Australia/Melbourne")
  550. >>> experiments_per_month = (
  551. ... Experiment.objects.annotate(month=TruncMonth("start_datetime", tzinfo=melb))
  552. ... .values("month")
  553. ... .annotate(experiments=Count("id"))
  554. ... )
  555. >>> for exp in experiments_per_month:
  556. ... print(exp["month"], exp["experiments"])
  557. ...
  558. 2015-06-01 00:00:00+10:00 1
  559. 2016-01-01 00:00:00+11:00 1
  560. 2014-06-01 00:00:00+10:00 1
  561. ``DateTimeField`` truncation
  562. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  563. .. class:: TruncDate(expression, tzinfo=None, **extra)
  564. .. attribute:: lookup_name = 'date'
  565. .. attribute:: output_field = DateField()
  566. ``TruncDate`` casts ``expression`` to a date rather than using the built-in SQL
  567. truncate function. It's also registered as a transform on ``DateTimeField`` as
  568. ``__date``.
  569. .. class:: TruncTime(expression, tzinfo=None, **extra)
  570. .. attribute:: lookup_name = 'time'
  571. .. attribute:: output_field = TimeField()
  572. ``TruncTime`` casts ``expression`` to a time rather than using the built-in SQL
  573. truncate function. It's also registered as a transform on ``DateTimeField`` as
  574. ``__time``.
  575. .. class:: TruncDay(expression, output_field=None, tzinfo=None, **extra)
  576. .. attribute:: kind = 'day'
  577. .. class:: TruncHour(expression, output_field=None, tzinfo=None, **extra)
  578. .. attribute:: kind = 'hour'
  579. .. class:: TruncMinute(expression, output_field=None, tzinfo=None, **extra)
  580. .. attribute:: kind = 'minute'
  581. .. class:: TruncSecond(expression, output_field=None, tzinfo=None, **extra)
  582. .. attribute:: kind = 'second'
  583. These are logically equivalent to ``Trunc('datetime_field', kind)``. They
  584. truncate all parts of the date up to ``kind`` and allow grouping or filtering
  585. datetimes with less precision. ``expression`` must have an ``output_field`` of
  586. ``DateTimeField``.
  587. Usage example:
  588. .. code-block:: pycon
  589. >>> from datetime import date, datetime, timezone
  590. >>> from django.db.models import Count
  591. >>> from django.db.models.functions import (
  592. ... TruncDate,
  593. ... TruncDay,
  594. ... TruncHour,
  595. ... TruncMinute,
  596. ... TruncSecond,
  597. ... )
  598. >>> import zoneinfo
  599. >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
  600. >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
  601. >>> melb = zoneinfo.ZoneInfo("Australia/Melbourne")
  602. >>> Experiment.objects.annotate(
  603. ... date=TruncDate("start_datetime"),
  604. ... day=TruncDay("start_datetime", tzinfo=melb),
  605. ... hour=TruncHour("start_datetime", tzinfo=melb),
  606. ... minute=TruncMinute("start_datetime"),
  607. ... second=TruncSecond("start_datetime"),
  608. ... ).values("date", "day", "hour", "minute", "second").get()
  609. {'date': datetime.date(2014, 6, 15),
  610. 'day': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=zoneinfo.ZoneInfo('Australia/Melbourne')),
  611. 'hour': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=zoneinfo.ZoneInfo('Australia/Melbourne')),
  612. 'minute': 'minute': datetime.datetime(2014, 6, 15, 14, 30, tzinfo=timezone.utc),
  613. 'second': datetime.datetime(2014, 6, 15, 14, 30, 50, tzinfo=timezone.utc)
  614. }
  615. ``TimeField`` truncation
  616. ~~~~~~~~~~~~~~~~~~~~~~~~
  617. .. class:: TruncHour(expression, output_field=None, tzinfo=None, **extra)
  618. :noindex:
  619. .. attribute:: kind = 'hour'
  620. .. class:: TruncMinute(expression, output_field=None, tzinfo=None, **extra)
  621. :noindex:
  622. .. attribute:: kind = 'minute'
  623. .. class:: TruncSecond(expression, output_field=None, tzinfo=None, **extra)
  624. :noindex:
  625. .. attribute:: kind = 'second'
  626. These are logically equivalent to ``Trunc('time_field', kind)``. They truncate
  627. all parts of the time up to ``kind`` which allows grouping or filtering times
  628. with less precision. ``expression`` can have an ``output_field`` of either
  629. ``TimeField`` or ``DateTimeField``.
  630. Since ``TimeField``\s don't have a date component, only ``Trunc`` subclasses
  631. that deal with time-parts can be used with ``TimeField``:
  632. .. code-block:: pycon
  633. >>> from datetime import datetime, timezone
  634. >>> from django.db.models import Count, TimeField
  635. >>> from django.db.models.functions import TruncHour
  636. >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
  637. >>> start2 = datetime(2014, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)
  638. >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)
  639. >>> Experiment.objects.create(start_datetime=start1, start_time=start1.time())
  640. >>> Experiment.objects.create(start_datetime=start2, start_time=start2.time())
  641. >>> Experiment.objects.create(start_datetime=start3, start_time=start3.time())
  642. >>> experiments_per_hour = (
  643. ... Experiment.objects.annotate(
  644. ... hour=TruncHour("start_datetime", output_field=TimeField()),
  645. ... )
  646. ... .values("hour")
  647. ... .annotate(experiments=Count("id"))
  648. ... )
  649. >>> for exp in experiments_per_hour:
  650. ... print(exp["hour"], exp["experiments"])
  651. ...
  652. 14:00:00 2
  653. 17:00:00 1
  654. >>> import zoneinfo
  655. >>> melb = zoneinfo.ZoneInfo("Australia/Melbourne")
  656. >>> experiments_per_hour = (
  657. ... Experiment.objects.annotate(
  658. ... hour=TruncHour("start_datetime", tzinfo=melb),
  659. ... )
  660. ... .values("hour")
  661. ... .annotate(experiments=Count("id"))
  662. ... )
  663. >>> for exp in experiments_per_hour:
  664. ... print(exp["hour"], exp["experiments"])
  665. ...
  666. 2014-06-16 00:00:00+10:00 2
  667. 2016-01-01 04:00:00+11:00 1
  668. .. _math-functions:
  669. Math Functions
  670. ==============
  671. We'll be using the following model in math function examples::
  672. class Vector(models.Model):
  673. x = models.FloatField()
  674. y = models.FloatField()
  675. ``Abs``
  676. -------
  677. .. class:: Abs(expression, **extra)
  678. Returns the absolute value of a numeric field or expression.
  679. Usage example:
  680. .. code-block:: pycon
  681. >>> from django.db.models.functions import Abs
  682. >>> Vector.objects.create(x=-0.5, y=1.1)
  683. >>> vector = Vector.objects.annotate(x_abs=Abs("x"), y_abs=Abs("y")).get()
  684. >>> vector.x_abs, vector.y_abs
  685. (0.5, 1.1)
  686. It can also be registered as a transform. For example:
  687. .. code-block:: pycon
  688. >>> from django.db.models import FloatField
  689. >>> from django.db.models.functions import Abs
  690. >>> FloatField.register_lookup(Abs)
  691. >>> # Get vectors inside the unit cube
  692. >>> vectors = Vector.objects.filter(x__abs__lt=1, y__abs__lt=1)
  693. ``ACos``
  694. --------
  695. .. class:: ACos(expression, **extra)
  696. Returns the arccosine of a numeric field or expression. The expression value
  697. must be within the range -1 to 1.
  698. Usage example:
  699. .. code-block:: pycon
  700. >>> from django.db.models.functions import ACos
  701. >>> Vector.objects.create(x=0.5, y=-0.9)
  702. >>> vector = Vector.objects.annotate(x_acos=ACos("x"), y_acos=ACos("y")).get()
  703. >>> vector.x_acos, vector.y_acos
  704. (1.0471975511965979, 2.6905658417935308)
  705. It can also be registered as a transform. For example:
  706. .. code-block:: pycon
  707. >>> from django.db.models import FloatField
  708. >>> from django.db.models.functions import ACos
  709. >>> FloatField.register_lookup(ACos)
  710. >>> # Get vectors whose arccosine is less than 1
  711. >>> vectors = Vector.objects.filter(x__acos__lt=1, y__acos__lt=1)
  712. ``ASin``
  713. --------
  714. .. class:: ASin(expression, **extra)
  715. Returns the arcsine of a numeric field or expression. The expression value must
  716. be in the range -1 to 1.
  717. Usage example:
  718. .. code-block:: pycon
  719. >>> from django.db.models.functions import ASin
  720. >>> Vector.objects.create(x=0, y=1)
  721. >>> vector = Vector.objects.annotate(x_asin=ASin("x"), y_asin=ASin("y")).get()
  722. >>> vector.x_asin, vector.y_asin
  723. (0.0, 1.5707963267948966)
  724. It can also be registered as a transform. For example:
  725. .. code-block:: pycon
  726. >>> from django.db.models import FloatField
  727. >>> from django.db.models.functions import ASin
  728. >>> FloatField.register_lookup(ASin)
  729. >>> # Get vectors whose arcsine is less than 1
  730. >>> vectors = Vector.objects.filter(x__asin__lt=1, y__asin__lt=1)
  731. ``ATan``
  732. --------
  733. .. class:: ATan(expression, **extra)
  734. Returns the arctangent of a numeric field or expression.
  735. Usage example:
  736. .. code-block:: pycon
  737. >>> from django.db.models.functions import ATan
  738. >>> Vector.objects.create(x=3.12, y=6.987)
  739. >>> vector = Vector.objects.annotate(x_atan=ATan("x"), y_atan=ATan("y")).get()
  740. >>> vector.x_atan, vector.y_atan
  741. (1.2606282660069106, 1.428638798133829)
  742. It can also be registered as a transform. For example:
  743. .. code-block:: pycon
  744. >>> from django.db.models import FloatField
  745. >>> from django.db.models.functions import ATan
  746. >>> FloatField.register_lookup(ATan)
  747. >>> # Get vectors whose arctangent is less than 2
  748. >>> vectors = Vector.objects.filter(x__atan__lt=2, y__atan__lt=2)
  749. ``ATan2``
  750. ---------
  751. .. class:: ATan2(expression1, expression2, **extra)
  752. Returns the arctangent of ``expression1 / expression2``.
  753. Usage example:
  754. .. code-block:: pycon
  755. >>> from django.db.models.functions import ATan2
  756. >>> Vector.objects.create(x=2.5, y=1.9)
  757. >>> vector = Vector.objects.annotate(atan2=ATan2("x", "y")).get()
  758. >>> vector.atan2
  759. 0.9209258773829491
  760. ``Ceil``
  761. --------
  762. .. class:: Ceil(expression, **extra)
  763. Returns the smallest integer greater than or equal to a numeric field or
  764. expression.
  765. Usage example:
  766. .. code-block:: pycon
  767. >>> from django.db.models.functions import Ceil
  768. >>> Vector.objects.create(x=3.12, y=7.0)
  769. >>> vector = Vector.objects.annotate(x_ceil=Ceil("x"), y_ceil=Ceil("y")).get()
  770. >>> vector.x_ceil, vector.y_ceil
  771. (4.0, 7.0)
  772. It can also be registered as a transform. For example:
  773. .. code-block:: pycon
  774. >>> from django.db.models import FloatField
  775. >>> from django.db.models.functions import Ceil
  776. >>> FloatField.register_lookup(Ceil)
  777. >>> # Get vectors whose ceil is less than 10
  778. >>> vectors = Vector.objects.filter(x__ceil__lt=10, y__ceil__lt=10)
  779. ``Cos``
  780. -------
  781. .. class:: Cos(expression, **extra)
  782. Returns the cosine of a numeric field or expression.
  783. Usage example:
  784. .. code-block:: pycon
  785. >>> from django.db.models.functions import Cos
  786. >>> Vector.objects.create(x=-8.0, y=3.1415926)
  787. >>> vector = Vector.objects.annotate(x_cos=Cos("x"), y_cos=Cos("y")).get()
  788. >>> vector.x_cos, vector.y_cos
  789. (-0.14550003380861354, -0.9999999999999986)
  790. It can also be registered as a transform. For example:
  791. .. code-block:: pycon
  792. >>> from django.db.models import FloatField
  793. >>> from django.db.models.functions import Cos
  794. >>> FloatField.register_lookup(Cos)
  795. >>> # Get vectors whose cosine is less than 0.5
  796. >>> vectors = Vector.objects.filter(x__cos__lt=0.5, y__cos__lt=0.5)
  797. ``Cot``
  798. -------
  799. .. class:: Cot(expression, **extra)
  800. Returns the cotangent of a numeric field or expression.
  801. Usage example:
  802. .. code-block:: pycon
  803. >>> from django.db.models.functions import Cot
  804. >>> Vector.objects.create(x=12.0, y=1.0)
  805. >>> vector = Vector.objects.annotate(x_cot=Cot("x"), y_cot=Cot("y")).get()
  806. >>> vector.x_cot, vector.y_cot
  807. (-1.5726734063976826, 0.642092615934331)
  808. It can also be registered as a transform. For example:
  809. .. code-block:: pycon
  810. >>> from django.db.models import FloatField
  811. >>> from django.db.models.functions import Cot
  812. >>> FloatField.register_lookup(Cot)
  813. >>> # Get vectors whose cotangent is less than 1
  814. >>> vectors = Vector.objects.filter(x__cot__lt=1, y__cot__lt=1)
  815. ``Degrees``
  816. -----------
  817. .. class:: Degrees(expression, **extra)
  818. Converts a numeric field or expression from radians to degrees.
  819. Usage example:
  820. .. code-block:: pycon
  821. >>> from django.db.models.functions import Degrees
  822. >>> Vector.objects.create(x=-1.57, y=3.14)
  823. >>> vector = Vector.objects.annotate(x_d=Degrees("x"), y_d=Degrees("y")).get()
  824. >>> vector.x_d, vector.y_d
  825. (-89.95437383553924, 179.9087476710785)
  826. It can also be registered as a transform. For example:
  827. .. code-block:: pycon
  828. >>> from django.db.models import FloatField
  829. >>> from django.db.models.functions import Degrees
  830. >>> FloatField.register_lookup(Degrees)
  831. >>> # Get vectors whose degrees are less than 360
  832. >>> vectors = Vector.objects.filter(x__degrees__lt=360, y__degrees__lt=360)
  833. ``Exp``
  834. -------
  835. .. class:: Exp(expression, **extra)
  836. Returns the value of ``e`` (the natural logarithm base) raised to the power of
  837. a numeric field or expression.
  838. Usage example:
  839. .. code-block:: pycon
  840. >>> from django.db.models.functions import Exp
  841. >>> Vector.objects.create(x=5.4, y=-2.0)
  842. >>> vector = Vector.objects.annotate(x_exp=Exp("x"), y_exp=Exp("y")).get()
  843. >>> vector.x_exp, vector.y_exp
  844. (221.40641620418717, 0.1353352832366127)
  845. It can also be registered as a transform. For example:
  846. .. code-block:: pycon
  847. >>> from django.db.models import FloatField
  848. >>> from django.db.models.functions import Exp
  849. >>> FloatField.register_lookup(Exp)
  850. >>> # Get vectors whose exp() is greater than 10
  851. >>> vectors = Vector.objects.filter(x__exp__gt=10, y__exp__gt=10)
  852. ``Floor``
  853. ---------
  854. .. class:: Floor(expression, **extra)
  855. Returns the largest integer value not greater than a numeric field or
  856. expression.
  857. Usage example:
  858. .. code-block:: pycon
  859. >>> from django.db.models.functions import Floor
  860. >>> Vector.objects.create(x=5.4, y=-2.3)
  861. >>> vector = Vector.objects.annotate(x_floor=Floor("x"), y_floor=Floor("y")).get()
  862. >>> vector.x_floor, vector.y_floor
  863. (5.0, -3.0)
  864. It can also be registered as a transform. For example:
  865. .. code-block:: pycon
  866. >>> from django.db.models import FloatField
  867. >>> from django.db.models.functions import Floor
  868. >>> FloatField.register_lookup(Floor)
  869. >>> # Get vectors whose floor() is greater than 10
  870. >>> vectors = Vector.objects.filter(x__floor__gt=10, y__floor__gt=10)
  871. ``Ln``
  872. ------
  873. .. class:: Ln(expression, **extra)
  874. Returns the natural logarithm a numeric field or expression.
  875. Usage example:
  876. .. code-block:: pycon
  877. >>> from django.db.models.functions import Ln
  878. >>> Vector.objects.create(x=5.4, y=233.0)
  879. >>> vector = Vector.objects.annotate(x_ln=Ln("x"), y_ln=Ln("y")).get()
  880. >>> vector.x_ln, vector.y_ln
  881. (1.6863989535702288, 5.4510384535657)
  882. It can also be registered as a transform. For example:
  883. .. code-block:: pycon
  884. >>> from django.db.models import FloatField
  885. >>> from django.db.models.functions import Ln
  886. >>> FloatField.register_lookup(Ln)
  887. >>> # Get vectors whose value greater than e
  888. >>> vectors = Vector.objects.filter(x__ln__gt=1, y__ln__gt=1)
  889. ``Log``
  890. -------
  891. .. class:: Log(expression1, expression2, **extra)
  892. Accepts two numeric fields or expressions and returns the logarithm of
  893. the second to base of the first.
  894. Usage example:
  895. .. code-block:: pycon
  896. >>> from django.db.models.functions import Log
  897. >>> Vector.objects.create(x=2.0, y=4.0)
  898. >>> vector = Vector.objects.annotate(log=Log("x", "y")).get()
  899. >>> vector.log
  900. 2.0
  901. ``Mod``
  902. -------
  903. .. class:: Mod(expression1, expression2, **extra)
  904. Accepts two numeric fields or expressions and returns the remainder of
  905. the first divided by the second (modulo operation).
  906. Usage example:
  907. .. code-block:: pycon
  908. >>> from django.db.models.functions import Mod
  909. >>> Vector.objects.create(x=5.4, y=2.3)
  910. >>> vector = Vector.objects.annotate(mod=Mod("x", "y")).get()
  911. >>> vector.mod
  912. 0.8
  913. ``Pi``
  914. ------
  915. .. class:: Pi(**extra)
  916. Returns the value of the mathematical constant ``π``.
  917. ``Power``
  918. ---------
  919. .. class:: Power(expression1, expression2, **extra)
  920. Accepts two numeric fields or expressions and returns the value of the first
  921. raised to the power of the second.
  922. Usage example:
  923. .. code-block:: pycon
  924. >>> from django.db.models.functions import Power
  925. >>> Vector.objects.create(x=2, y=-2)
  926. >>> vector = Vector.objects.annotate(power=Power("x", "y")).get()
  927. >>> vector.power
  928. 0.25
  929. ``Radians``
  930. -----------
  931. .. class:: Radians(expression, **extra)
  932. Converts a numeric field or expression from degrees to radians.
  933. Usage example:
  934. .. code-block:: pycon
  935. >>> from django.db.models.functions import Radians
  936. >>> Vector.objects.create(x=-90, y=180)
  937. >>> vector = Vector.objects.annotate(x_r=Radians("x"), y_r=Radians("y")).get()
  938. >>> vector.x_r, vector.y_r
  939. (-1.5707963267948966, 3.141592653589793)
  940. It can also be registered as a transform. For example:
  941. .. code-block:: pycon
  942. >>> from django.db.models import FloatField
  943. >>> from django.db.models.functions import Radians
  944. >>> FloatField.register_lookup(Radians)
  945. >>> # Get vectors whose radians are less than 1
  946. >>> vectors = Vector.objects.filter(x__radians__lt=1, y__radians__lt=1)
  947. ``Random``
  948. ----------
  949. .. class:: Random(**extra)
  950. Returns a random value in the range ``0.0 ≤ x < 1.0``.
  951. ``Round``
  952. ---------
  953. .. class:: Round(expression, precision=0, **extra)
  954. Rounds a numeric field or expression to ``precision`` (must be an integer)
  955. decimal places. By default, it rounds to the nearest integer. Whether half
  956. values are rounded up or down depends on the database.
  957. Usage example:
  958. .. code-block:: pycon
  959. >>> from django.db.models.functions import Round
  960. >>> Vector.objects.create(x=5.4, y=-2.37)
  961. >>> vector = Vector.objects.annotate(x_r=Round("x"), y_r=Round("y", precision=1)).get()
  962. >>> vector.x_r, vector.y_r
  963. (5.0, -2.4)
  964. It can also be registered as a transform. For example:
  965. .. code-block:: pycon
  966. >>> from django.db.models import FloatField
  967. >>> from django.db.models.functions import Round
  968. >>> FloatField.register_lookup(Round)
  969. >>> # Get vectors whose round() is less than 20
  970. >>> vectors = Vector.objects.filter(x__round__lt=20, y__round__lt=20)
  971. ``Sign``
  972. --------
  973. .. class:: Sign(expression, **extra)
  974. Returns the sign (-1, 0, 1) of a numeric field or expression.
  975. Usage example:
  976. .. code-block:: pycon
  977. >>> from django.db.models.functions import Sign
  978. >>> Vector.objects.create(x=5.4, y=-2.3)
  979. >>> vector = Vector.objects.annotate(x_sign=Sign("x"), y_sign=Sign("y")).get()
  980. >>> vector.x_sign, vector.y_sign
  981. (1, -1)
  982. It can also be registered as a transform. For example:
  983. .. code-block:: pycon
  984. >>> from django.db.models import FloatField
  985. >>> from django.db.models.functions import Sign
  986. >>> FloatField.register_lookup(Sign)
  987. >>> # Get vectors whose signs of components are less than 0.
  988. >>> vectors = Vector.objects.filter(x__sign__lt=0, y__sign__lt=0)
  989. ``Sin``
  990. -------
  991. .. class:: Sin(expression, **extra)
  992. Returns the sine of a numeric field or expression.
  993. Usage example:
  994. .. code-block:: pycon
  995. >>> from django.db.models.functions import Sin
  996. >>> Vector.objects.create(x=5.4, y=-2.3)
  997. >>> vector = Vector.objects.annotate(x_sin=Sin("x"), y_sin=Sin("y")).get()
  998. >>> vector.x_sin, vector.y_sin
  999. (-0.7727644875559871, -0.7457052121767203)
  1000. It can also be registered as a transform. For example:
  1001. .. code-block:: pycon
  1002. >>> from django.db.models import FloatField
  1003. >>> from django.db.models.functions import Sin
  1004. >>> FloatField.register_lookup(Sin)
  1005. >>> # Get vectors whose sin() is less than 0
  1006. >>> vectors = Vector.objects.filter(x__sin__lt=0, y__sin__lt=0)
  1007. ``Sqrt``
  1008. --------
  1009. .. class:: Sqrt(expression, **extra)
  1010. Returns the square root of a nonnegative numeric field or expression.
  1011. Usage example:
  1012. .. code-block:: pycon
  1013. >>> from django.db.models.functions import Sqrt
  1014. >>> Vector.objects.create(x=4.0, y=12.0)
  1015. >>> vector = Vector.objects.annotate(x_sqrt=Sqrt("x"), y_sqrt=Sqrt("y")).get()
  1016. >>> vector.x_sqrt, vector.y_sqrt
  1017. (2.0, 3.46410)
  1018. It can also be registered as a transform. For example:
  1019. .. code-block:: pycon
  1020. >>> from django.db.models import FloatField
  1021. >>> from django.db.models.functions import Sqrt
  1022. >>> FloatField.register_lookup(Sqrt)
  1023. >>> # Get vectors whose sqrt() is less than 5
  1024. >>> vectors = Vector.objects.filter(x__sqrt__lt=5, y__sqrt__lt=5)
  1025. ``Tan``
  1026. -------
  1027. .. class:: Tan(expression, **extra)
  1028. Returns the tangent of a numeric field or expression.
  1029. Usage example:
  1030. .. code-block:: pycon
  1031. >>> from django.db.models.functions import Tan
  1032. >>> Vector.objects.create(x=0, y=12)
  1033. >>> vector = Vector.objects.annotate(x_tan=Tan("x"), y_tan=Tan("y")).get()
  1034. >>> vector.x_tan, vector.y_tan
  1035. (0.0, -0.6358599286615808)
  1036. It can also be registered as a transform. For example:
  1037. .. code-block:: pycon
  1038. >>> from django.db.models import FloatField
  1039. >>> from django.db.models.functions import Tan
  1040. >>> FloatField.register_lookup(Tan)
  1041. >>> # Get vectors whose tangent is less than 0
  1042. >>> vectors = Vector.objects.filter(x__tan__lt=0, y__tan__lt=0)
  1043. .. _text-functions:
  1044. Text functions
  1045. ==============
  1046. ``Chr``
  1047. -------
  1048. .. class:: Chr(expression, **extra)
  1049. Accepts a numeric field or expression and returns the text representation of
  1050. the expression as a single character. It works the same as Python's :func:`chr`
  1051. function.
  1052. Like :class:`Length`, it can be registered as a transform on ``IntegerField``.
  1053. The default lookup name is ``chr``.
  1054. Usage example:
  1055. .. code-block:: pycon
  1056. >>> from django.db.models.functions import Chr
  1057. >>> Author.objects.create(name="Margaret Smith")
  1058. >>> author = Author.objects.filter(name__startswith=Chr(ord("M"))).get()
  1059. >>> print(author.name)
  1060. Margaret Smith
  1061. ``Concat``
  1062. ----------
  1063. .. class:: Concat(*expressions, **extra)
  1064. Accepts a list of at least two text fields or expressions and returns the
  1065. concatenated text. Each argument must be of a text or char type. If you want
  1066. to concatenate a ``TextField()`` with a ``CharField()``, then be sure to tell
  1067. Django that the ``output_field`` should be a ``TextField()``. Specifying an
  1068. ``output_field`` is also required when concatenating a ``Value`` as in the
  1069. example below.
  1070. This function will never have a null result. On backends where a null argument
  1071. results in the entire expression being null, Django will ensure that each null
  1072. part is converted to an empty string first.
  1073. Usage example:
  1074. .. code-block:: pycon
  1075. >>> # Get the display name as "name (goes_by)"
  1076. >>> from django.db.models import CharField, Value as V
  1077. >>> from django.db.models.functions import Concat
  1078. >>> Author.objects.create(name="Margaret Smith", goes_by="Maggie")
  1079. >>> author = Author.objects.annotate(
  1080. ... screen_name=Concat("name", V(" ("), "goes_by", V(")"), output_field=CharField())
  1081. ... ).get()
  1082. >>> print(author.screen_name)
  1083. Margaret Smith (Maggie)
  1084. ``Left``
  1085. --------
  1086. .. class:: Left(expression, length, **extra)
  1087. Returns the first ``length`` characters of the given text field or expression.
  1088. Usage example:
  1089. .. code-block:: pycon
  1090. >>> from django.db.models.functions import Left
  1091. >>> Author.objects.create(name="Margaret Smith")
  1092. >>> author = Author.objects.annotate(first_initial=Left("name", 1)).get()
  1093. >>> print(author.first_initial)
  1094. M
  1095. ``Length``
  1096. ----------
  1097. .. class:: Length(expression, **extra)
  1098. Accepts a single text field or expression and returns the number of characters
  1099. the value has. If the expression is null, then the length will also be null.
  1100. Usage example:
  1101. .. code-block:: pycon
  1102. >>> # Get the length of the name and goes_by fields
  1103. >>> from django.db.models.functions import Length
  1104. >>> Author.objects.create(name="Margaret Smith")
  1105. >>> author = Author.objects.annotate(
  1106. ... name_length=Length("name"), goes_by_length=Length("goes_by")
  1107. ... ).get()
  1108. >>> print(author.name_length, author.goes_by_length)
  1109. (14, None)
  1110. It can also be registered as a transform. For example:
  1111. .. code-block:: pycon
  1112. >>> from django.db.models import CharField
  1113. >>> from django.db.models.functions import Length
  1114. >>> CharField.register_lookup(Length)
  1115. >>> # Get authors whose name is longer than 7 characters
  1116. >>> authors = Author.objects.filter(name__length__gt=7)
  1117. ``Lower``
  1118. ---------
  1119. .. class:: Lower(expression, **extra)
  1120. Accepts a single text field or expression and returns the lowercase
  1121. representation.
  1122. It can also be registered as a transform as described in :class:`Length`.
  1123. Usage example:
  1124. .. code-block:: pycon
  1125. >>> from django.db.models.functions import Lower
  1126. >>> Author.objects.create(name="Margaret Smith")
  1127. >>> author = Author.objects.annotate(name_lower=Lower("name")).get()
  1128. >>> print(author.name_lower)
  1129. margaret smith
  1130. ``LPad``
  1131. --------
  1132. .. class:: LPad(expression, length, fill_text=Value(' '), **extra)
  1133. Returns the value of the given text field or expression padded on the left side
  1134. with ``fill_text`` so that the resulting value is ``length`` characters long.
  1135. The default ``fill_text`` is a space.
  1136. Usage example:
  1137. .. code-block:: pycon
  1138. >>> from django.db.models import Value
  1139. >>> from django.db.models.functions import LPad
  1140. >>> Author.objects.create(name="John", alias="j")
  1141. >>> Author.objects.update(name=LPad("name", 8, Value("abc")))
  1142. 1
  1143. >>> print(Author.objects.get(alias="j").name)
  1144. abcaJohn
  1145. ``LTrim``
  1146. ---------
  1147. .. class:: LTrim(expression, **extra)
  1148. Similar to :class:`~django.db.models.functions.Trim`, but removes only leading
  1149. spaces.
  1150. ``MD5``
  1151. -------
  1152. .. class:: MD5(expression, **extra)
  1153. Accepts a single text field or expression and returns the MD5 hash of the
  1154. string.
  1155. It can also be registered as a transform as described in :class:`Length`.
  1156. Usage example:
  1157. .. code-block:: pycon
  1158. >>> from django.db.models.functions import MD5
  1159. >>> Author.objects.create(name="Margaret Smith")
  1160. >>> author = Author.objects.annotate(name_md5=MD5("name")).get()
  1161. >>> print(author.name_md5)
  1162. 749fb689816b2db85f5b169c2055b247
  1163. ``Ord``
  1164. -------
  1165. .. class:: Ord(expression, **extra)
  1166. Accepts a single text field or expression and returns the Unicode code point
  1167. value for the first character of that expression. It works similar to Python's
  1168. :func:`ord` function, but an exception isn't raised if the expression is more
  1169. than one character long.
  1170. It can also be registered as a transform as described in :class:`Length`.
  1171. The default lookup name is ``ord``.
  1172. Usage example:
  1173. .. code-block:: pycon
  1174. >>> from django.db.models.functions import Ord
  1175. >>> Author.objects.create(name="Margaret Smith")
  1176. >>> author = Author.objects.annotate(name_code_point=Ord("name")).get()
  1177. >>> print(author.name_code_point)
  1178. 77
  1179. ``Repeat``
  1180. ----------
  1181. .. class:: Repeat(expression, number, **extra)
  1182. Returns the value of the given text field or expression repeated ``number``
  1183. times.
  1184. Usage example:
  1185. .. code-block:: pycon
  1186. >>> from django.db.models.functions import Repeat
  1187. >>> Author.objects.create(name="John", alias="j")
  1188. >>> Author.objects.update(name=Repeat("name", 3))
  1189. 1
  1190. >>> print(Author.objects.get(alias="j").name)
  1191. JohnJohnJohn
  1192. ``Replace``
  1193. -----------
  1194. .. class:: Replace(expression, text, replacement=Value(''), **extra)
  1195. Replaces all occurrences of ``text`` with ``replacement`` in ``expression``.
  1196. The default replacement text is the empty string. The arguments to the function
  1197. are case-sensitive.
  1198. Usage example:
  1199. .. code-block:: pycon
  1200. >>> from django.db.models import Value
  1201. >>> from django.db.models.functions import Replace
  1202. >>> Author.objects.create(name="Margaret Johnson")
  1203. >>> Author.objects.create(name="Margaret Smith")
  1204. >>> Author.objects.update(name=Replace("name", Value("Margaret"), Value("Margareth")))
  1205. 2
  1206. >>> Author.objects.values("name")
  1207. <QuerySet [{'name': 'Margareth Johnson'}, {'name': 'Margareth Smith'}]>
  1208. ``Reverse``
  1209. -----------
  1210. .. class:: Reverse(expression, **extra)
  1211. Accepts a single text field or expression and returns the characters of that
  1212. expression in reverse order.
  1213. It can also be registered as a transform as described in :class:`Length`. The
  1214. default lookup name is ``reverse``.
  1215. Usage example:
  1216. .. code-block:: pycon
  1217. >>> from django.db.models.functions import Reverse
  1218. >>> Author.objects.create(name="Margaret Smith")
  1219. >>> author = Author.objects.annotate(backward=Reverse("name")).get()
  1220. >>> print(author.backward)
  1221. htimS teragraM
  1222. ``Right``
  1223. ---------
  1224. .. class:: Right(expression, length, **extra)
  1225. Returns the last ``length`` characters of the given text field or expression.
  1226. Usage example:
  1227. .. code-block:: pycon
  1228. >>> from django.db.models.functions import Right
  1229. >>> Author.objects.create(name="Margaret Smith")
  1230. >>> author = Author.objects.annotate(last_letter=Right("name", 1)).get()
  1231. >>> print(author.last_letter)
  1232. h
  1233. ``RPad``
  1234. --------
  1235. .. class:: RPad(expression, length, fill_text=Value(' '), **extra)
  1236. Similar to :class:`~django.db.models.functions.LPad`, but pads on the right
  1237. side.
  1238. ``RTrim``
  1239. ---------
  1240. .. class:: RTrim(expression, **extra)
  1241. Similar to :class:`~django.db.models.functions.Trim`, but removes only trailing
  1242. spaces.
  1243. ``SHA1``, ``SHA224``, ``SHA256``, ``SHA384``, and ``SHA512``
  1244. ------------------------------------------------------------
  1245. .. class:: SHA1(expression, **extra)
  1246. .. class:: SHA224(expression, **extra)
  1247. .. class:: SHA256(expression, **extra)
  1248. .. class:: SHA384(expression, **extra)
  1249. .. class:: SHA512(expression, **extra)
  1250. Accepts a single text field or expression and returns the particular hash of
  1251. the string.
  1252. They can also be registered as transforms as described in :class:`Length`.
  1253. Usage example:
  1254. .. code-block:: pycon
  1255. >>> from django.db.models.functions import SHA1
  1256. >>> Author.objects.create(name="Margaret Smith")
  1257. >>> author = Author.objects.annotate(name_sha1=SHA1("name")).get()
  1258. >>> print(author.name_sha1)
  1259. b87efd8a6c991c390be5a68e8a7945a7851c7e5c
  1260. .. admonition:: PostgreSQL
  1261. The `pgcrypto extension <https://www.postgresql.org/docs/current/
  1262. pgcrypto.html>`_ must be installed. You can use the
  1263. :class:`~django.contrib.postgres.operations.CryptoExtension` migration
  1264. operation to install it.
  1265. .. admonition:: Oracle
  1266. Oracle doesn't support the ``SHA224`` function.
  1267. ``StrIndex``
  1268. ------------
  1269. .. class:: StrIndex(string, substring, **extra)
  1270. Returns a positive integer corresponding to the 1-indexed position of the first
  1271. occurrence of ``substring`` inside ``string``, or 0 if ``substring`` is not
  1272. found.
  1273. Usage example:
  1274. .. code-block:: pycon
  1275. >>> from django.db.models import Value as V
  1276. >>> from django.db.models.functions import StrIndex
  1277. >>> Author.objects.create(name="Margaret Smith")
  1278. >>> Author.objects.create(name="Smith, Margaret")
  1279. >>> Author.objects.create(name="Margaret Jackson")
  1280. >>> Author.objects.filter(name="Margaret Jackson").annotate(
  1281. ... smith_index=StrIndex("name", V("Smith"))
  1282. ... ).get().smith_index
  1283. 0
  1284. >>> authors = Author.objects.annotate(smith_index=StrIndex("name", V("Smith"))).filter(
  1285. ... smith_index__gt=0
  1286. ... )
  1287. <QuerySet [<Author: Margaret Smith>, <Author: Smith, Margaret>]>
  1288. .. warning::
  1289. In MySQL, a database table's :ref:`collation<mysql-collation>` determines
  1290. whether string comparisons (such as the ``expression`` and ``substring`` of
  1291. this function) are case-sensitive. Comparisons are case-insensitive by
  1292. default.
  1293. ``Substr``
  1294. ----------
  1295. .. class:: Substr(expression, pos, length=None, **extra)
  1296. Returns a substring of length ``length`` from the field or expression starting
  1297. at position ``pos``. The position is 1-indexed, so the position must be greater
  1298. than 0. If ``length`` is ``None``, then the rest of the string will be returned.
  1299. Usage example:
  1300. .. code-block:: pycon
  1301. >>> # Set the alias to the first 5 characters of the name as lowercase
  1302. >>> from django.db.models.functions import Lower, Substr
  1303. >>> Author.objects.create(name="Margaret Smith")
  1304. >>> Author.objects.update(alias=Lower(Substr("name", 1, 5)))
  1305. 1
  1306. >>> print(Author.objects.get(name="Margaret Smith").alias)
  1307. marga
  1308. ``Trim``
  1309. --------
  1310. .. class:: Trim(expression, **extra)
  1311. Returns the value of the given text field or expression with leading and
  1312. trailing spaces removed.
  1313. Usage example:
  1314. .. code-block:: pycon
  1315. >>> from django.db.models.functions import Trim
  1316. >>> Author.objects.create(name=" John ", alias="j")
  1317. >>> Author.objects.update(name=Trim("name"))
  1318. 1
  1319. >>> print(Author.objects.get(alias="j").name)
  1320. John
  1321. ``Upper``
  1322. ---------
  1323. .. class:: Upper(expression, **extra)
  1324. Accepts a single text field or expression and returns the uppercase
  1325. representation.
  1326. It can also be registered as a transform as described in :class:`Length`.
  1327. Usage example:
  1328. .. code-block:: pycon
  1329. >>> from django.db.models.functions import Upper
  1330. >>> Author.objects.create(name="Margaret Smith")
  1331. >>> author = Author.objects.annotate(name_upper=Upper("name")).get()
  1332. >>> print(author.name_upper)
  1333. MARGARET SMITH
  1334. .. _window-functions:
  1335. Window functions
  1336. ================
  1337. There are a number of functions to use in a
  1338. :class:`~django.db.models.expressions.Window` expression for computing the rank
  1339. of elements or the :class:`Ntile` of some rows.
  1340. ``CumeDist``
  1341. ------------
  1342. .. class:: CumeDist(*expressions, **extra)
  1343. Calculates the cumulative distribution of a value within a window or partition.
  1344. The cumulative distribution is defined as the number of rows preceding or
  1345. peered with the current row divided by the total number of rows in the frame.
  1346. ``DenseRank``
  1347. -------------
  1348. .. class:: DenseRank(*expressions, **extra)
  1349. Equivalent to :class:`Rank` but does not have gaps.
  1350. ``FirstValue``
  1351. --------------
  1352. .. class:: FirstValue(expression, **extra)
  1353. Returns the value evaluated at the row that's the first row of the window
  1354. frame, or ``None`` if no such value exists.
  1355. ``Lag``
  1356. -------
  1357. .. class:: Lag(expression, offset=1, default=None, **extra)
  1358. Calculates the value offset by ``offset``, and if no row exists there, returns
  1359. ``default``.
  1360. ``default`` must have the same type as the ``expression``, however, this is
  1361. only validated by the database and not in Python.
  1362. .. admonition:: MariaDB and ``default``
  1363. MariaDB `doesn't support <https://jira.mariadb.org/browse/MDEV-12981>`_
  1364. the ``default`` parameter.
  1365. ``LastValue``
  1366. -------------
  1367. .. class:: LastValue(expression, **extra)
  1368. Comparable to :class:`FirstValue`, it calculates the last value in a given
  1369. frame clause.
  1370. ``Lead``
  1371. --------
  1372. .. class:: Lead(expression, offset=1, default=None, **extra)
  1373. Calculates the leading value in a given :ref:`frame <window-frames>`. Both
  1374. ``offset`` and ``default`` are evaluated with respect to the current row.
  1375. ``default`` must have the same type as the ``expression``, however, this is
  1376. only validated by the database and not in Python.
  1377. .. admonition:: MariaDB and ``default``
  1378. MariaDB `doesn't support <https://jira.mariadb.org/browse/MDEV-12981>`_
  1379. the ``default`` parameter.
  1380. ``NthValue``
  1381. ------------
  1382. .. class:: NthValue(expression, nth=1, **extra)
  1383. Computes the row relative to the offset ``nth`` (must be a positive value)
  1384. within the window. Returns ``None`` if no row exists.
  1385. Some databases may handle a nonexistent nth-value differently. For example,
  1386. Oracle returns an empty string rather than ``None`` for character-based
  1387. expressions. Django doesn't do any conversions in these cases.
  1388. ``Ntile``
  1389. ---------
  1390. .. class:: Ntile(num_buckets=1, **extra)
  1391. Calculates a partition for each of the rows in the frame clause, distributing
  1392. numbers as evenly as possible between 1 and ``num_buckets``. If the rows don't
  1393. divide evenly into a number of buckets, one or more buckets will be represented
  1394. more frequently.
  1395. ``PercentRank``
  1396. ---------------
  1397. .. class:: PercentRank(*expressions, **extra)
  1398. Computes the relative rank of the rows in the frame clause. This computation is
  1399. equivalent to evaluating:
  1400. .. code-block:: text
  1401. (rank - 1) / (total rows - 1)
  1402. The following table explains the calculation for the relative rank of a row:
  1403. ===== ===== ==== ============ =============
  1404. Row # Value Rank Calculation Relative Rank
  1405. ===== ===== ==== ============ =============
  1406. 1 15 1 (1-1)/(7-1) 0.0000
  1407. 2 20 2 (2-1)/(7-1) 0.1666
  1408. 3 20 2 (2-1)/(7-1) 0.1666
  1409. 4 20 2 (2-1)/(7-1) 0.1666
  1410. 5 30 5 (5-1)/(7-1) 0.6666
  1411. 6 30 5 (5-1)/(7-1) 0.6666
  1412. 7 40 7 (7-1)/(7-1) 1.0000
  1413. ===== ===== ==== ============ =============
  1414. ``Rank``
  1415. --------
  1416. .. class:: Rank(*expressions, **extra)
  1417. Comparable to :class:`RowNumber`, this function ranks rows in the window. The
  1418. computed rank contains gaps. Use :class:`DenseRank` to compute rank without
  1419. gaps.
  1420. ``RowNumber``
  1421. -------------
  1422. .. class:: RowNumber(*expressions, **extra)
  1423. Computes the row number according to the ordering of either the frame clause
  1424. or the ordering of the whole query if there is no partitioning of the
  1425. :ref:`window frame <window-frames>`.