database-functions.txt 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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. .. _date-functions:
  112. Date functions
  113. ==============
  114. We'll be using the following model in examples of each function::
  115. class Experiment(models.Model):
  116. start_datetime = models.DateTimeField()
  117. start_date = models.DateField(null=True, blank=True)
  118. start_time = models.TimeField(null=True, blank=True)
  119. end_datetime = models.DateTimeField(null=True, blank=True)
  120. end_date = models.DateField(null=True, blank=True)
  121. end_time = models.TimeField(null=True, blank=True)
  122. ``Extract``
  123. -----------
  124. .. class:: Extract(expression, lookup_name=None, tzinfo=None, **extra)
  125. Extracts a component of a date as a number.
  126. Takes an ``expression`` representing a ``DateField``, ``DateTimeField``,
  127. ``TimeField``, or ``DurationField`` and a ``lookup_name``, and returns the part
  128. of the date referenced by ``lookup_name`` as an ``IntegerField``.
  129. Django usually uses the databases' extract function, so you may use any
  130. ``lookup_name`` that your database supports. A ``tzinfo`` subclass, usually
  131. provided by ``pytz``, can be passed to extract a value in a specific timezone.
  132. Given the datetime ``2015-06-15 23:30:01.000321+00:00``, the built-in
  133. ``lookup_name``\s return:
  134. * "year": 2015
  135. * "quarter": 2
  136. * "month": 6
  137. * "day": 15
  138. * "week": 25
  139. * "week_day": 2
  140. * "hour": 23
  141. * "minute": 30
  142. * "second": 1
  143. If a different timezone like ``Australia/Melbourne`` is active in Django, then
  144. the datetime is converted to the timezone before the value is extracted. The
  145. timezone offset for Melbourne in the example date above is +10:00. The values
  146. returned when this timezone is active will be the same as above except for:
  147. * "day": 16
  148. * "week_day": 3
  149. * "hour": 9
  150. .. admonition:: ``week_day`` values
  151. The ``week_day`` ``lookup_type`` is calculated differently from most
  152. databases and from Python's standard functions. This function will return
  153. ``1`` for Sunday, ``2`` for Monday, through ``7`` for Saturday.
  154. The equivalent calculation in Python is::
  155. >>> from datetime import datetime
  156. >>> dt = datetime(2015, 6, 15)
  157. >>> (dt.isoweekday() % 7) + 1
  158. 2
  159. .. admonition:: ``week`` values
  160. The ``week`` ``lookup_type`` is calculated based on `ISO-8601
  161. <https://en.wikipedia.org/wiki/ISO-8601>`_, i.e.,
  162. a week starts on a Monday. The first week of a year is the one that
  163. contains the year's first Thursday, i.e. the first week has the majority
  164. (four or more) of its days in the year. The value returned is in the range
  165. 1 to 52 or 53.
  166. Each ``lookup_name`` above has a corresponding ``Extract`` subclass (listed
  167. below) that should typically be used instead of the more verbose equivalent,
  168. e.g. use ``ExtractYear(...)`` rather than ``Extract(..., lookup_name='year')``.
  169. Usage example::
  170. >>> from datetime import datetime
  171. >>> from django.db.models.functions import Extract
  172. >>> start = datetime(2015, 6, 15)
  173. >>> end = datetime(2015, 7, 2)
  174. >>> Experiment.objects.create(
  175. ... start_datetime=start, start_date=start.date(),
  176. ... end_datetime=end, end_date=end.date())
  177. >>> # Add the experiment start year as a field in the QuerySet.
  178. >>> experiment = Experiment.objects.annotate(
  179. ... start_year=Extract('start_datetime', 'year')).get()
  180. >>> experiment.start_year
  181. 2015
  182. >>> # How many experiments completed in the same year in which they started?
  183. >>> Experiment.objects.filter(
  184. ... start_datetime__year=Extract('end_datetime', 'year')).count()
  185. 1
  186. ``DateField`` extracts
  187. ~~~~~~~~~~~~~~~~~~~~~~
  188. .. class:: ExtractYear(expression, tzinfo=None, **extra)
  189. .. attribute:: lookup_name = 'year'
  190. .. class:: ExtractMonth(expression, tzinfo=None, **extra)
  191. .. attribute:: lookup_name = 'month'
  192. .. class:: ExtractDay(expression, tzinfo=None, **extra)
  193. .. attribute:: lookup_name = 'day'
  194. .. class:: ExtractWeekDay(expression, tzinfo=None, **extra)
  195. .. attribute:: lookup_name = 'week_day'
  196. .. class:: ExtractWeek(expression, tzinfo=None, **extra)
  197. .. attribute:: lookup_name = 'week'
  198. .. class:: ExtractQuarter(expression, tzinfo=None, **extra)
  199. .. attribute:: lookup_name = 'quarter'
  200. These are logically equivalent to ``Extract('date_field', lookup_name)``. Each
  201. class is also a ``Transform`` registered on ``DateField`` and ``DateTimeField``
  202. as ``__(lookup_name)``, e.g. ``__year``.
  203. Since ``DateField``\s don't have a time component, only ``Extract`` subclasses
  204. that deal with date-parts can be used with ``DateField``::
  205. >>> from datetime import datetime
  206. >>> from django.utils import timezone
  207. >>> from django.db.models.functions import (
  208. ... ExtractDay, ExtractMonth, ExtractQuarter, ExtractWeek,
  209. ... ExtractWeekDay, ExtractYear,
  210. ... )
  211. >>> start_2015 = datetime(2015, 6, 15, 23, 30, 1, tzinfo=timezone.utc)
  212. >>> end_2015 = datetime(2015, 6, 16, 13, 11, 27, tzinfo=timezone.utc)
  213. >>> Experiment.objects.create(
  214. ... start_datetime=start_2015, start_date=start_2015.date(),
  215. ... end_datetime=end_2015, end_date=end_2015.date())
  216. >>> Experiment.objects.annotate(
  217. ... year=ExtractYear('start_date'),
  218. ... quarter=ExtractQuarter('start_date'),
  219. ... month=ExtractMonth('start_date'),
  220. ... week=ExtractWeek('start_date'),
  221. ... day=ExtractDay('start_date'),
  222. ... weekday=ExtractWeekDay('start_date'),
  223. ... ).values('year', 'quarter', 'month', 'week', 'day', 'weekday').get(
  224. ... end_date__year=ExtractYear('start_date'),
  225. ... )
  226. {'year': 2015, 'quarter': 2, 'month': 6, 'week': 25, 'day': 15, 'weekday': 2}
  227. ``DateTimeField`` extracts
  228. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  229. In addition to the following, all extracts for ``DateField`` listed above may
  230. also be used on ``DateTimeField``\s .
  231. .. class:: ExtractHour(expression, tzinfo=None, **extra)
  232. .. attribute:: lookup_name = 'hour'
  233. .. class:: ExtractMinute(expression, tzinfo=None, **extra)
  234. .. attribute:: lookup_name = 'minute'
  235. .. class:: ExtractSecond(expression, tzinfo=None, **extra)
  236. .. attribute:: lookup_name = 'second'
  237. These are logically equivalent to ``Extract('datetime_field', lookup_name)``.
  238. Each class is also a ``Transform`` registered on ``DateTimeField`` as
  239. ``__(lookup_name)``, e.g. ``__minute``.
  240. ``DateTimeField`` examples::
  241. >>> from datetime import datetime
  242. >>> from django.utils import timezone
  243. >>> from django.db.models.functions import (
  244. ... ExtractDay, ExtractHour, ExtractMinute, ExtractMonth,
  245. ... ExtractQuarter, ExtractSecond, ExtractWeek, ExtractWeekDay,
  246. ... ExtractYear,
  247. ... )
  248. >>> start_2015 = datetime(2015, 6, 15, 23, 30, 1, tzinfo=timezone.utc)
  249. >>> end_2015 = datetime(2015, 6, 16, 13, 11, 27, tzinfo=timezone.utc)
  250. >>> Experiment.objects.create(
  251. ... start_datetime=start_2015, start_date=start_2015.date(),
  252. ... end_datetime=end_2015, end_date=end_2015.date())
  253. >>> Experiment.objects.annotate(
  254. ... year=ExtractYear('start_datetime'),
  255. ... quarter=ExtractQuarter('start_datetime'),
  256. ... month=ExtractMonth('start_datetime'),
  257. ... week=ExtractWeek('start_datetime'),
  258. ... day=ExtractDay('start_datetime'),
  259. ... weekday=ExtractWeekDay('start_datetime'),
  260. ... hour=ExtractHour('start_datetime'),
  261. ... minute=ExtractMinute('start_datetime'),
  262. ... second=ExtractSecond('start_datetime'),
  263. ... ).values(
  264. ... 'year', 'month', 'week', 'day', 'weekday', 'hour', 'minute', 'second',
  265. ... ).get(end_datetime__year=ExtractYear('start_datetime'))
  266. {'year': 2015, 'quarter': 2, 'month': 6, 'week': 25, 'day': 15, 'weekday': 2,
  267. 'hour': 23, 'minute': 30, 'second': 1}
  268. When :setting:`USE_TZ` is ``True`` then datetimes are stored in the database
  269. in UTC. If a different timezone is active in Django, the datetime is converted
  270. to that timezone before the value is extracted. The example below converts to
  271. the Melbourne timezone (UTC +10:00), which changes the day, weekday, and hour
  272. values that are returned::
  273. >>> import pytz
  274. >>> melb = pytz.timezone('Australia/Melbourne') # UTC+10:00
  275. >>> with timezone.override(melb):
  276. ... Experiment.objects.annotate(
  277. ... day=ExtractDay('start_datetime'),
  278. ... weekday=ExtractWeekDay('start_datetime'),
  279. ... hour=ExtractHour('start_datetime'),
  280. ... ).values('day', 'weekday', 'hour').get(
  281. ... end_datetime__year=ExtractYear('start_datetime'),
  282. ... )
  283. {'day': 16, 'weekday': 3, 'hour': 9}
  284. Explicitly passing the timezone to the ``Extract`` function behaves in the same
  285. way, and takes priority over an active timezone::
  286. >>> import pytz
  287. >>> melb = pytz.timezone('Australia/Melbourne')
  288. >>> Experiment.objects.annotate(
  289. ... day=ExtractDay('start_datetime', tzinfo=melb),
  290. ... weekday=ExtractWeekDay('start_datetime', tzinfo=melb),
  291. ... hour=ExtractHour('start_datetime', tzinfo=melb),
  292. ... ).values('day', 'weekday', 'hour').get(
  293. ... end_datetime__year=ExtractYear('start_datetime'),
  294. ... )
  295. {'day': 16, 'weekday': 3, 'hour': 9}
  296. ``Now``
  297. -------
  298. .. class:: Now()
  299. Returns the database server's current date and time when the query is executed,
  300. typically using the SQL ``CURRENT_TIMESTAMP``.
  301. Usage example::
  302. >>> from django.db.models.functions import Now
  303. >>> Article.objects.filter(published__lte=Now())
  304. <QuerySet [<Article: How to Django>]>
  305. .. admonition:: PostgreSQL considerations
  306. On PostgreSQL, the SQL ``CURRENT_TIMESTAMP`` returns the time that the
  307. current transaction started. Therefore for cross-database compatibility,
  308. ``Now()`` uses ``STATEMENT_TIMESTAMP`` instead. If you need the transaction
  309. timestamp, use :class:`django.contrib.postgres.functions.TransactionNow`.
  310. ``Trunc``
  311. ---------
  312. .. class:: Trunc(expression, kind, output_field=None, tzinfo=None, **extra)
  313. Truncates a date up to a significant component.
  314. When you only care if something happened in a particular year, hour, or day,
  315. but not the exact second, then ``Trunc`` (and its subclasses) can be useful to
  316. filter or aggregate your data. For example, you can use ``Trunc`` to calculate
  317. the number of sales per day.
  318. ``Trunc`` takes a single ``expression``, representing a ``DateField``,
  319. ``TimeField``, or ``DateTimeField``, a ``kind`` representing a date or time
  320. part, and an ``output_field`` that's either ``DateTimeField()``,
  321. ``TimeField()``, or ``DateField()``. It returns a datetime, date, or time
  322. depending on ``output_field``, with fields up to ``kind`` set to their minimum
  323. value. If ``output_field`` is omitted, it will default to the ``output_field``
  324. of ``expression``. A ``tzinfo`` subclass, usually provided by ``pytz``, can be
  325. passed to truncate a value in a specific timezone.
  326. Given the datetime ``2015-06-15 14:30:50.000321+00:00``, the built-in ``kind``\s
  327. return:
  328. * "year": 2015-01-01 00:00:00+00:00
  329. * "quarter": 2015-04-01 00:00:00+00:00
  330. * "month": 2015-06-01 00:00:00+00:00
  331. * "week": 2015-06-15 00:00:00+00:00
  332. * "day": 2015-06-15 00:00:00+00:00
  333. * "hour": 2015-06-15 14:00:00+00:00
  334. * "minute": 2015-06-15 14:30:00+00:00
  335. * "second": 2015-06-15 14:30:50+00:00
  336. If a different timezone like ``Australia/Melbourne`` is active in Django, then
  337. the datetime is converted to the new timezone before the value is truncated.
  338. The timezone offset for Melbourne in the example date above is +10:00. The
  339. values returned when this timezone is active will be:
  340. * "year": 2015-01-01 00:00:00+11:00
  341. * "quarter": 2015-04-01 00:00:00+10:00
  342. * "month": 2015-06-01 00:00:00+10:00
  343. * "week": 2015-06-16 00:00:00+10:00
  344. * "day": 2015-06-16 00:00:00+10:00
  345. * "hour": 2015-06-16 00:00:00+10:00
  346. * "minute": 2015-06-16 00:30:00+10:00
  347. * "second": 2015-06-16 00:30:50+10:00
  348. The year has an offset of +11:00 because the result transitioned into daylight
  349. saving time.
  350. Each ``kind`` above has a corresponding ``Trunc`` subclass (listed below) that
  351. should typically be used instead of the more verbose equivalent,
  352. e.g. use ``TruncYear(...)`` rather than ``Trunc(..., kind='year')``.
  353. The subclasses are all defined as transforms, but they aren't registered with
  354. any fields, because the obvious lookup names are already reserved by the
  355. ``Extract`` subclasses.
  356. Usage example::
  357. >>> from datetime import datetime
  358. >>> from django.db.models import Count, DateTimeField
  359. >>> from django.db.models.functions import Trunc
  360. >>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 30, 50, 321))
  361. >>> Experiment.objects.create(start_datetime=datetime(2015, 6, 15, 14, 40, 2, 123))
  362. >>> Experiment.objects.create(start_datetime=datetime(2015, 12, 25, 10, 5, 27, 999))
  363. >>> experiments_per_day = Experiment.objects.annotate(
  364. ... start_day=Trunc('start_datetime', 'day', output_field=DateTimeField())
  365. ... ).values('start_day').annotate(experiments=Count('id'))
  366. >>> for exp in experiments_per_day:
  367. ... print(exp['start_day'], exp['experiments'])
  368. ...
  369. 2015-06-15 00:00:00 2
  370. 2015-12-25 00:00:00 1
  371. >>> experiments = Experiment.objects.annotate(
  372. ... start_day=Trunc('start_datetime', 'day', output_field=DateTimeField())
  373. ... ).filter(start_day=datetime(2015, 6, 15))
  374. >>> for exp in experiments:
  375. ... print(exp.start_datetime)
  376. ...
  377. 2015-06-15 14:30:50.000321
  378. 2015-06-15 14:40:02.000123
  379. ``DateField`` truncation
  380. ~~~~~~~~~~~~~~~~~~~~~~~~
  381. .. class:: TruncYear(expression, output_field=None, tzinfo=None, **extra)
  382. .. attribute:: kind = 'year'
  383. .. class:: TruncMonth(expression, output_field=None, tzinfo=None, **extra)
  384. .. attribute:: kind = 'month'
  385. .. class:: TruncWeek(expression, output_field=None, tzinfo=None, **extra)
  386. .. versionadded:: 2.1
  387. Truncates to midnight on the Monday of the week.
  388. .. attribute:: kind = 'week'
  389. .. class:: TruncQuarter(expression, output_field=None, tzinfo=None, **extra)
  390. .. attribute:: kind = 'quarter'
  391. These are logically equivalent to ``Trunc('date_field', kind)``. They truncate
  392. all parts of the date up to ``kind`` which allows grouping or filtering dates
  393. with less precision. ``expression`` can have an ``output_field`` of either
  394. ``DateField`` or ``DateTimeField``.
  395. Since ``DateField``\s don't have a time component, only ``Trunc`` subclasses
  396. that deal with date-parts can be used with ``DateField``::
  397. >>> from datetime import datetime
  398. >>> from django.db.models import Count
  399. >>> from django.db.models.functions import TruncMonth, TruncYear
  400. >>> from django.utils import timezone
  401. >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
  402. >>> start2 = datetime(2015, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)
  403. >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)
  404. >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
  405. >>> Experiment.objects.create(start_datetime=start2, start_date=start2.date())
  406. >>> Experiment.objects.create(start_datetime=start3, start_date=start3.date())
  407. >>> experiments_per_year = Experiment.objects.annotate(
  408. ... year=TruncYear('start_date')).values('year').annotate(
  409. ... experiments=Count('id'))
  410. >>> for exp in experiments_per_year:
  411. ... print(exp['year'], exp['experiments'])
  412. ...
  413. 2014-01-01 1
  414. 2015-01-01 2
  415. >>> import pytz
  416. >>> melb = pytz.timezone('Australia/Melbourne')
  417. >>> experiments_per_month = Experiment.objects.annotate(
  418. ... month=TruncMonth('start_datetime', tzinfo=melb)).values('month').annotate(
  419. ... experiments=Count('id'))
  420. >>> for exp in experiments_per_month:
  421. ... print(exp['month'], exp['experiments'])
  422. ...
  423. 2015-06-01 00:00:00+10:00 1
  424. 2016-01-01 00:00:00+11:00 1
  425. 2014-06-01 00:00:00+10:00 1
  426. ``DateTimeField`` truncation
  427. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  428. .. class:: TruncDate(expression, **extra)
  429. .. attribute:: lookup_name = 'date'
  430. .. attribute:: output_field = DateField()
  431. ``TruncDate`` casts ``expression`` to a date rather than using the built-in SQL
  432. truncate function. It's also registered as a transform on ``DateTimeField`` as
  433. ``__date``.
  434. .. class:: TruncTime(expression, **extra)
  435. .. attribute:: lookup_name = 'time'
  436. .. attribute:: output_field = TimeField()
  437. ``TruncTime`` casts ``expression`` to a time rather than using the built-in SQL
  438. truncate function. It's also registered as a transform on ``DateTimeField`` as
  439. ``__time``.
  440. .. class:: TruncDay(expression, output_field=None, tzinfo=None, **extra)
  441. .. attribute:: kind = 'day'
  442. .. class:: TruncHour(expression, output_field=None, tzinfo=None, **extra)
  443. .. attribute:: kind = 'hour'
  444. .. class:: TruncMinute(expression, output_field=None, tzinfo=None, **extra)
  445. .. attribute:: kind = 'minute'
  446. .. class:: TruncSecond(expression, output_field=None, tzinfo=None, **extra)
  447. .. attribute:: kind = 'second'
  448. These are logically equivalent to ``Trunc('datetime_field', kind)``. They
  449. truncate all parts of the date up to ``kind`` and allow grouping or filtering
  450. datetimes with less precision. ``expression`` must have an ``output_field`` of
  451. ``DateTimeField``.
  452. Usage example::
  453. >>> from datetime import date, datetime
  454. >>> from django.db.models import Count
  455. >>> from django.db.models.functions import (
  456. ... TruncDate, TruncDay, TruncHour, TruncMinute, TruncSecond,
  457. ... )
  458. >>> from django.utils import timezone
  459. >>> import pytz
  460. >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
  461. >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
  462. >>> melb = pytz.timezone('Australia/Melbourne')
  463. >>> Experiment.objects.annotate(
  464. ... date=TruncDate('start_datetime'),
  465. ... day=TruncDay('start_datetime', tzinfo=melb),
  466. ... hour=TruncHour('start_datetime', tzinfo=melb),
  467. ... minute=TruncMinute('start_datetime'),
  468. ... second=TruncSecond('start_datetime'),
  469. ... ).values('date', 'day', 'hour', 'minute', 'second').get()
  470. {'date': datetime.date(2014, 6, 15),
  471. 'day': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=<DstTzInfo 'Australia/Melbourne' AEST+10:00:00 STD>),
  472. 'hour': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=<DstTzInfo 'Australia/Melbourne' AEST+10:00:00 STD>),
  473. 'minute': 'minute': datetime.datetime(2014, 6, 15, 14, 30, tzinfo=<UTC>),
  474. 'second': datetime.datetime(2014, 6, 15, 14, 30, 50, tzinfo=<UTC>)
  475. }
  476. ``TimeField`` truncation
  477. ~~~~~~~~~~~~~~~~~~~~~~~~
  478. .. class:: TruncHour(expression, output_field=None, tzinfo=None, **extra)
  479. .. attribute:: kind = 'hour'
  480. .. class:: TruncMinute(expression, output_field=None, tzinfo=None, **extra)
  481. .. attribute:: kind = 'minute'
  482. .. class:: TruncSecond(expression, output_field=None, tzinfo=None, **extra)
  483. .. attribute:: kind = 'second'
  484. These are logically equivalent to ``Trunc('time_field', kind)``. They truncate
  485. all parts of the time up to ``kind`` which allows grouping or filtering times
  486. with less precision. ``expression`` can have an ``output_field`` of either
  487. ``TimeField`` or ``DateTimeField``.
  488. Since ``TimeField``\s don't have a date component, only ``Trunc`` subclasses
  489. that deal with time-parts can be used with ``TimeField``::
  490. >>> from datetime import datetime
  491. >>> from django.db.models import Count, TimeField
  492. >>> from django.db.models.functions import TruncHour
  493. >>> from django.utils import timezone
  494. >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
  495. >>> start2 = datetime(2014, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)
  496. >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)
  497. >>> Experiment.objects.create(start_datetime=start1, start_time=start1.time())
  498. >>> Experiment.objects.create(start_datetime=start2, start_time=start2.time())
  499. >>> Experiment.objects.create(start_datetime=start3, start_time=start3.time())
  500. >>> experiments_per_hour = Experiment.objects.annotate(
  501. ... hour=TruncHour('start_datetime', output_field=TimeField()),
  502. ... ).values('hour').annotate(experiments=Count('id'))
  503. >>> for exp in experiments_per_hour:
  504. ... print(exp['hour'], exp['experiments'])
  505. ...
  506. 14:00:00 2
  507. 17:00:00 1
  508. >>> import pytz
  509. >>> melb = pytz.timezone('Australia/Melbourne')
  510. >>> experiments_per_hour = Experiment.objects.annotate(
  511. ... hour=TruncHour('start_datetime', tzinfo=melb),
  512. ... ).values('hour').annotate(experiments=Count('id'))
  513. >>> for exp in experiments_per_hour:
  514. ... print(exp['hour'], exp['experiments'])
  515. ...
  516. 2014-06-16 00:00:00+10:00 2
  517. 2016-01-01 04:00:00+11:00 1
  518. .. _text-functions:
  519. Text functions
  520. ==============
  521. ``Chr``
  522. -------
  523. .. class:: Chr(expression, **extra)
  524. .. versionadded:: 2.1
  525. Accepts a numeric field or expression and returns the text representation of
  526. the expression as a single character. It works the same as Python's :func:`chr`
  527. function.
  528. Like :class:`Length`, it can be registered as a transform on ``IntegerField``.
  529. The default lookup name is ``chr``.
  530. Usage example::
  531. >>> from django.db.models.functions import Chr
  532. >>> Author.objects.create(name='Margaret Smith')
  533. >>> author = Author.objects.filter(name__startswith=Chr(ord('M'))).get()
  534. >>> print(author.name)
  535. Margaret Smith
  536. ``Concat``
  537. ----------
  538. .. class:: Concat(*expressions, **extra)
  539. Accepts a list of at least two text fields or expressions and returns the
  540. concatenated text. Each argument must be of a text or char type. If you want
  541. to concatenate a ``TextField()`` with a ``CharField()``, then be sure to tell
  542. Django that the ``output_field`` should be a ``TextField()``. Specifying an
  543. ``output_field`` is also required when concatenating a ``Value`` as in the
  544. example below.
  545. This function will never have a null result. On backends where a null argument
  546. results in the entire expression being null, Django will ensure that each null
  547. part is converted to an empty string first.
  548. Usage example::
  549. >>> # Get the display name as "name (goes_by)"
  550. >>> from django.db.models import CharField, Value as V
  551. >>> from django.db.models.functions import Concat
  552. >>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')
  553. >>> author = Author.objects.annotate(
  554. ... screen_name=Concat(
  555. ... 'name', V(' ('), 'goes_by', V(')'),
  556. ... output_field=CharField()
  557. ... )
  558. ... ).get()
  559. >>> print(author.screen_name)
  560. Margaret Smith (Maggie)
  561. ``Left``
  562. --------
  563. .. class:: Left(expression, length, **extra)
  564. .. versionadded:: 2.1
  565. Returns the first ``length`` characters of the given text field or expression.
  566. Usage example::
  567. >>> from django.db.models.functions import Left
  568. >>> Author.objects.create(name='Margaret Smith')
  569. >>> author = Author.objects.annotate(first_initial=Left('name', 1)).get()
  570. >>> print(author.first_initial)
  571. M
  572. ``Length``
  573. ----------
  574. .. class:: Length(expression, **extra)
  575. Accepts a single text field or expression and returns the number of characters
  576. the value has. If the expression is null, then the length will also be null.
  577. Usage example::
  578. >>> # Get the length of the name and goes_by fields
  579. >>> from django.db.models.functions import Length
  580. >>> Author.objects.create(name='Margaret Smith')
  581. >>> author = Author.objects.annotate(
  582. ... name_length=Length('name'),
  583. ... goes_by_length=Length('goes_by')).get()
  584. >>> print(author.name_length, author.goes_by_length)
  585. (14, None)
  586. It can also be registered as a transform. For example::
  587. >>> from django.db.models import CharField
  588. >>> from django.db.models.functions import Length
  589. >>> CharField.register_lookup(Length)
  590. >>> # Get authors whose name is longer than 7 characters
  591. >>> authors = Author.objects.filter(name__length__gt=7)
  592. ``Lower``
  593. ---------
  594. .. class:: Lower(expression, **extra)
  595. Accepts a single text field or expression and returns the lowercase
  596. representation.
  597. It can also be registered as a transform as described in :class:`Length`.
  598. Usage example::
  599. >>> from django.db.models.functions import Lower
  600. >>> Author.objects.create(name='Margaret Smith')
  601. >>> author = Author.objects.annotate(name_lower=Lower('name')).get()
  602. >>> print(author.name_lower)
  603. margaret smith
  604. ``LPad``
  605. --------
  606. .. class:: LPad(expression, length, fill_text=Value(' '), **extra)
  607. .. versionadded:: 2.1
  608. Returns the value of the given text field or expression padded on the left side
  609. with ``fill_text`` so that the resulting value is ``length`` characters long.
  610. The default ``fill_text`` is a space.
  611. Usage example::
  612. >>> from django.db.models import Value
  613. >>> from django.db.models.functions import LPad
  614. >>> Author.objects.create(name='John', alias='j')
  615. >>> Author.objects.update(name=LPad('name', 8, Value('abc')))
  616. 1
  617. >>> print(Author.objects.get(alias='j').name)
  618. abcaJohn
  619. ``LTrim``
  620. ---------
  621. .. class:: LTrim(expression, **extra)
  622. .. versionadded:: 2.1
  623. Similar to :class:`~django.db.models.functions.Trim`, but removes only leading
  624. spaces.
  625. ``Ord``
  626. -------
  627. .. class:: Ord(expression, **extra)
  628. .. versionadded:: 2.1
  629. Accepts a single text field or expression and returns the Unicode code point
  630. value for the first character of that expression. It works similar to Python's
  631. :func:`ord` function, but an exception isn't raised if the expression is more
  632. than one character long.
  633. It can also be registered as a transform as described in :class:`Length`.
  634. The default lookup name is ``ord``.
  635. Usage example::
  636. >>> from django.db.models.functions import Ord
  637. >>> Author.objects.create(name='Margaret Smith')
  638. >>> author = Author.objects.annotate(name_code_point=Ord('name')).get()
  639. >>> print(author.name_code_point)
  640. 77
  641. ``Repeat``
  642. ----------
  643. .. class:: Repeat(expression, number, **extra)
  644. .. versionadded:: 2.1
  645. Returns the value of the given text field or expression repeated ``number``
  646. times.
  647. Usage example::
  648. >>> from django.db.models.functions import Repeat
  649. >>> Author.objects.create(name='John', alias='j')
  650. >>> Author.objects.update(name=Repeat('name', 3))
  651. 1
  652. >>> print(Author.objects.get(alias='j').name)
  653. JohnJohnJohn
  654. ``Replace``
  655. -----------
  656. .. class:: Replace(expression, text, replacement=Value(''), **extra)
  657. .. versionadded:: 2.1
  658. Replaces all occurrences of ``text`` with ``replacement`` in ``expression``.
  659. The default replacement text is the empty string. The arguments to the function
  660. are case-sensitive.
  661. Usage example::
  662. >>> from django.db.models import Value
  663. >>> from django.db.models.functions import Replace
  664. >>> Author.objects.create(name='Margaret Johnson')
  665. >>> Author.objects.create(name='Margaret Smith')
  666. >>> Author.objects.update(name=Replace('name', Value('Margaret'), Value('Margareth')))
  667. 2
  668. >>> Author.objects.values('name')
  669. <QuerySet [{'name': 'Margareth Johnson'}, {'name': 'Margareth Smith'}]>
  670. ``Right``
  671. ---------
  672. .. class:: Right(expression, length, **extra)
  673. .. versionadded:: 2.1
  674. Returns the last ``length`` characters of the given text field or expression.
  675. Usage example::
  676. >>> from django.db.models.functions import Right
  677. >>> Author.objects.create(name='Margaret Smith')
  678. >>> author = Author.objects.annotate(last_letter=Right('name', 1)).get()
  679. >>> print(author.last_letter)
  680. h
  681. ``RPad``
  682. --------
  683. .. class:: RPad(expression, length, fill_text=Value(' '), **extra)
  684. .. versionadded:: 2.1
  685. Similar to :class:`~django.db.models.functions.LPad`, but pads on the right
  686. side.
  687. ``RTrim``
  688. ---------
  689. .. class:: RTrim(expression, **extra)
  690. .. versionadded:: 2.1
  691. Similar to :class:`~django.db.models.functions.Trim`, but removes only trailing
  692. spaces.
  693. ``StrIndex``
  694. ------------
  695. .. class:: StrIndex(string, substring, **extra)
  696. Returns a positive integer corresponding to the 1-indexed position of the first
  697. occurrence of ``substring`` inside ``string``, or 0 if ``substring`` is not
  698. found.
  699. Usage example::
  700. >>> from django.db.models import Value as V
  701. >>> from django.db.models.functions import StrIndex
  702. >>> Author.objects.create(name='Margaret Smith')
  703. >>> Author.objects.create(name='Smith, Margaret')
  704. >>> Author.objects.create(name='Margaret Jackson')
  705. >>> Author.objects.filter(name='Margaret Jackson').annotate(
  706. ... smith_index=StrIndex('name', V('Smith'))
  707. ... ).get().smith_index
  708. 0
  709. >>> authors = Author.objects.annotate(
  710. ... smith_index=StrIndex('name', V('Smith'))
  711. ... ).filter(smith_index__gt=0)
  712. <QuerySet [<Author: Margaret Smith>, <Author: Smith, Margaret>]>
  713. .. warning::
  714. In MySQL, a database table's :ref:`collation<mysql-collation>` determines
  715. whether string comparisons (such as the ``expression`` and ``substring`` of
  716. this function) are case-sensitive. Comparisons are case-insensitive by
  717. default.
  718. ``Substr``
  719. ----------
  720. .. class:: Substr(expression, pos, length=None, **extra)
  721. Returns a substring of length ``length`` from the field or expression starting
  722. at position ``pos``. The position is 1-indexed, so the position must be greater
  723. than 0. If ``length`` is ``None``, then the rest of the string will be returned.
  724. Usage example::
  725. >>> # Set the alias to the first 5 characters of the name as lowercase
  726. >>> from django.db.models.functions import Lower, Substr
  727. >>> Author.objects.create(name='Margaret Smith')
  728. >>> Author.objects.update(alias=Lower(Substr('name', 1, 5)))
  729. 1
  730. >>> print(Author.objects.get(name='Margaret Smith').alias)
  731. marga
  732. ``Trim``
  733. --------
  734. .. class:: Trim(expression, **extra)
  735. .. versionadded:: 2.1
  736. Returns the value of the given text field or expression with leading and
  737. trailing spaces removed.
  738. Usage example::
  739. >>> from django.db.models.functions import Trim
  740. >>> Author.objects.create(name=' John ', alias='j')
  741. >>> Author.objects.update(name=Trim('name'))
  742. 1
  743. >>> print(Author.objects.get(alias='j').name)
  744. John
  745. ``Upper``
  746. ---------
  747. .. class:: Upper(expression, **extra)
  748. Accepts a single text field or expression and returns the uppercase
  749. representation.
  750. It can also be registered as a transform as described in :class:`Length`.
  751. Usage example::
  752. >>> from django.db.models.functions import Upper
  753. >>> Author.objects.create(name='Margaret Smith')
  754. >>> author = Author.objects.annotate(name_upper=Upper('name')).get()
  755. >>> print(author.name_upper)
  756. MARGARET SMITH
  757. .. _window-functions:
  758. Window functions
  759. ================
  760. There are a number of functions to use in a
  761. :class:`~django.db.models.expressions.Window` expression for computing the rank
  762. of elements or the :class:`Ntile` of some rows.
  763. ``CumeDist``
  764. ------------
  765. .. class:: CumeDist(*expressions, **extra)
  766. Calculates the cumulative distribution of a value within a window or partition.
  767. The cumulative distribution is defined as the number of rows preceding or
  768. peered with the current row divided by the total number of rows in the frame.
  769. ``DenseRank``
  770. -------------
  771. .. class:: DenseRank(*expressions, **extra)
  772. Equivalent to :class:`Rank` but does not have gaps.
  773. ``FirstValue``
  774. --------------
  775. .. class:: FirstValue(expression, **extra)
  776. Returns the value evaluated at the row that's the first row of the window
  777. frame, or ``None`` if no such value exists.
  778. ``Lag``
  779. -------
  780. .. class:: Lag(expression, offset=1, default=None, **extra)
  781. Calculates the value offset by ``offset``, and if no row exists there, returns
  782. ``default``.
  783. ``default`` must have the same type as the ``expression``, however, this is
  784. only validated by the database and not in Python.
  785. ``LastValue``
  786. -------------
  787. .. class:: LastValue(expression, **extra)
  788. Comparable to :class:`FirstValue`, it calculates the last value in a given
  789. frame clause.
  790. ``Lead``
  791. --------
  792. .. class:: Lead(expression, offset=1, default=None, **extra)
  793. Calculates the leading value in a given :ref:`frame <window-frames>`. Both
  794. ``offset`` and ``default`` are evaluated with respect to the current row.
  795. ``default`` must have the same type as the ``expression``, however, this is
  796. only validated by the database and not in Python.
  797. ``NthValue``
  798. ------------
  799. .. class:: NthValue(expression, nth=1, **extra)
  800. Computes the row relative to the offset ``nth`` (must be a positive value)
  801. within the window. Returns ``None`` if no row exists.
  802. Some databases may handle a nonexistent nth-value differently. For example,
  803. Oracle returns an empty string rather than ``None`` for character-based
  804. expressions. Django doesn't do any conversions in these cases.
  805. ``Ntile``
  806. ---------
  807. .. class:: Ntile(num_buckets=1, **extra)
  808. Calculates a partition for each of the rows in the frame clause, distributing
  809. numbers as evenly as possible between 1 and ``num_buckets``. If the rows don't
  810. divide evenly into a number of buckets, one or more buckets will be represented
  811. more frequently.
  812. ``PercentRank``
  813. ---------------
  814. .. class:: PercentRank(*expressions, **extra)
  815. Computes the percentile rank of the rows in the frame clause. This
  816. computation is equivalent to evaluating::
  817. (rank - 1) / (total rows - 1)
  818. The following table explains the calculation for the percentile rank of a row:
  819. ===== ===== ==== ============ ============
  820. Row # Value Rank Calculation Percent Rank
  821. ===== ===== ==== ============ ============
  822. 1 15 1 (1-1)/(7-1) 0.0000
  823. 2 20 2 (2-1)/(7-1) 0.1666
  824. 3 20 2 (2-1)/(7-1) 0.1666
  825. 4 20 2 (2-1)/(7-1) 0.1666
  826. 5 30 5 (5-1)/(7-1) 0.6666
  827. 6 30 5 (5-1)/(7-1) 0.6666
  828. 7 40 7 (7-1)/(7-1) 1.0000
  829. ===== ===== ==== ============ ============
  830. ``Rank``
  831. --------
  832. .. class:: Rank(*expressions, **extra)
  833. Comparable to ``RowNumber``, this function ranks rows in the window. The
  834. computed rank contains gaps. Use :class:`DenseRank` to compute rank without
  835. gaps.
  836. ``RowNumber``
  837. -------------
  838. .. class:: RowNumber(*expressions, **extra)
  839. Computes the row number according to the ordering of either the frame clause
  840. or the ordering of the whole query if there is no partitioning of the
  841. :ref:`window frame <window-frames>`.