database-functions.txt 57 KB

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