database-functions.txt 38 KB

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