2
0

database-functions.txt 60 KB

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