database-functions.txt 36 KB

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