database-functions.txt 55 KB

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