database-functions.txt 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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. * "day": 2015-06-15 00:00:00+00:00
  334. * "hour": 2015-06-15 14:00:00+00:00
  335. * "minute": 2015-06-15 14:30:00+00:00
  336. * "second": 2015-06-15 14:30:50+00:00
  337. If a different timezone like ``Australia/Melbourne`` is active in Django, then
  338. the datetime is converted to the new timezone before the value is truncated.
  339. The timezone offset for Melbourne in the example date above is +10:00. The
  340. values returned when this timezone is active will be:
  341. * "year": 2015-01-01 00:00:00+11:00
  342. * "quarter": 2015-04-01 00:00:00+10:00
  343. * "month": 2015-06-01 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:: TruncQuarter(expression, output_field=None, tzinfo=None, **extra)
  386. .. versionadded:: 2.0
  387. .. attribute:: kind = 'quarter'
  388. These are logically equivalent to ``Trunc('date_field', kind)``. They truncate
  389. all parts of the date up to ``kind`` which allows grouping or filtering dates
  390. with less precision. ``expression`` can have an ``output_field`` of either
  391. ``DateField`` or ``DateTimeField``.
  392. Since ``DateField``\s don't have a time component, only ``Trunc`` subclasses
  393. that deal with date-parts can be used with ``DateField``::
  394. >>> from datetime import datetime
  395. >>> from django.db.models import Count
  396. >>> from django.db.models.functions import TruncMonth, TruncYear
  397. >>> from django.utils import timezone
  398. >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
  399. >>> start2 = datetime(2015, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)
  400. >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)
  401. >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
  402. >>> Experiment.objects.create(start_datetime=start2, start_date=start2.date())
  403. >>> Experiment.objects.create(start_datetime=start3, start_date=start3.date())
  404. >>> experiments_per_year = Experiment.objects.annotate(
  405. ... year=TruncYear('start_date')).values('year').annotate(
  406. ... experiments=Count('id'))
  407. >>> for exp in experiments_per_year:
  408. ... print(exp['year'], exp['experiments'])
  409. ...
  410. 2014-01-01 1
  411. 2015-01-01 2
  412. >>> import pytz
  413. >>> melb = pytz.timezone('Australia/Melbourne')
  414. >>> experiments_per_month = Experiment.objects.annotate(
  415. ... month=TruncMonth('start_datetime', tzinfo=melb)).values('month').annotate(
  416. ... experiments=Count('id'))
  417. >>> for exp in experiments_per_month:
  418. ... print(exp['month'], exp['experiments'])
  419. ...
  420. 2015-06-01 00:00:00+10:00 1
  421. 2016-01-01 00:00:00+11:00 1
  422. 2014-06-01 00:00:00+10:00 1
  423. ``DateTimeField`` truncation
  424. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  425. .. class:: TruncDate(expression, **extra)
  426. .. attribute:: lookup_name = 'date'
  427. .. attribute:: output_field = DateField()
  428. ``TruncDate`` casts ``expression`` to a date rather than using the built-in SQL
  429. truncate function. It's also registered as a transform on ``DateTimeField`` as
  430. ``__date``.
  431. .. class:: TruncTime(expression, **extra)
  432. .. attribute:: lookup_name = 'time'
  433. .. attribute:: output_field = TimeField()
  434. ``TruncTime`` casts ``expression`` to a time rather than using the built-in SQL
  435. truncate function. It's also registered as a transform on ``DateTimeField`` as
  436. ``__time``.
  437. .. class:: TruncDay(expression, output_field=None, tzinfo=None, **extra)
  438. .. attribute:: kind = 'day'
  439. .. class:: TruncHour(expression, output_field=None, tzinfo=None, **extra)
  440. .. attribute:: kind = 'hour'
  441. .. class:: TruncMinute(expression, output_field=None, tzinfo=None, **extra)
  442. .. attribute:: kind = 'minute'
  443. .. class:: TruncSecond(expression, output_field=None, tzinfo=None, **extra)
  444. .. attribute:: kind = 'second'
  445. These are logically equivalent to ``Trunc('datetime_field', kind)``. They
  446. truncate all parts of the date up to ``kind`` and allow grouping or filtering
  447. datetimes with less precision. ``expression`` must have an ``output_field`` of
  448. ``DateTimeField``.
  449. Usage example::
  450. >>> from datetime import date, datetime
  451. >>> from django.db.models import Count
  452. >>> from django.db.models.functions import (
  453. ... TruncDate, TruncDay, TruncHour, TruncMinute, TruncSecond,
  454. ... )
  455. >>> from django.utils import timezone
  456. >>> import pytz
  457. >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
  458. >>> Experiment.objects.create(start_datetime=start1, start_date=start1.date())
  459. >>> melb = pytz.timezone('Australia/Melbourne')
  460. >>> Experiment.objects.annotate(
  461. ... date=TruncDate('start_datetime'),
  462. ... day=TruncDay('start_datetime', tzinfo=melb),
  463. ... hour=TruncHour('start_datetime', tzinfo=melb),
  464. ... minute=TruncMinute('start_datetime'),
  465. ... second=TruncSecond('start_datetime'),
  466. ... ).values('date', 'day', 'hour', 'minute', 'second').get()
  467. {'date': datetime.date(2014, 6, 15),
  468. 'day': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=<DstTzInfo 'Australia/Melbourne' AEST+10:00:00 STD>),
  469. 'hour': datetime.datetime(2014, 6, 16, 0, 0, tzinfo=<DstTzInfo 'Australia/Melbourne' AEST+10:00:00 STD>),
  470. 'minute': 'minute': datetime.datetime(2014, 6, 15, 14, 30, tzinfo=<UTC>),
  471. 'second': datetime.datetime(2014, 6, 15, 14, 30, 50, tzinfo=<UTC>)
  472. }
  473. ``TimeField`` truncation
  474. ~~~~~~~~~~~~~~~~~~~~~~~~
  475. .. class:: TruncHour(expression, output_field=None, tzinfo=None, **extra)
  476. .. attribute:: kind = 'hour'
  477. .. class:: TruncMinute(expression, output_field=None, tzinfo=None, **extra)
  478. .. attribute:: kind = 'minute'
  479. .. class:: TruncSecond(expression, output_field=None, tzinfo=None, **extra)
  480. .. attribute:: kind = 'second'
  481. These are logically equivalent to ``Trunc('time_field', kind)``. They truncate
  482. all parts of the time up to ``kind`` which allows grouping or filtering times
  483. with less precision. ``expression`` can have an ``output_field`` of either
  484. ``TimeField`` or ``DateTimeField``.
  485. Since ``TimeField``\s don't have a date component, only ``Trunc`` subclasses
  486. that deal with time-parts can be used with ``TimeField``::
  487. >>> from datetime import datetime
  488. >>> from django.db.models import Count, TimeField
  489. >>> from django.db.models.functions import TruncHour
  490. >>> from django.utils import timezone
  491. >>> start1 = datetime(2014, 6, 15, 14, 30, 50, 321, tzinfo=timezone.utc)
  492. >>> start2 = datetime(2014, 6, 15, 14, 40, 2, 123, tzinfo=timezone.utc)
  493. >>> start3 = datetime(2015, 12, 31, 17, 5, 27, 999, tzinfo=timezone.utc)
  494. >>> Experiment.objects.create(start_datetime=start1, start_time=start1.time())
  495. >>> Experiment.objects.create(start_datetime=start2, start_time=start2.time())
  496. >>> Experiment.objects.create(start_datetime=start3, start_time=start3.time())
  497. >>> experiments_per_hour = Experiment.objects.annotate(
  498. ... hour=TruncHour('start_datetime', output_field=TimeField()),
  499. ... ).values('hour').annotate(experiments=Count('id'))
  500. >>> for exp in experiments_per_hour:
  501. ... print(exp['hour'], exp['experiments'])
  502. ...
  503. 14:00:00 2
  504. 17:00:00 1
  505. >>> import pytz
  506. >>> melb = pytz.timezone('Australia/Melbourne')
  507. >>> experiments_per_hour = Experiment.objects.annotate(
  508. ... hour=TruncHour('start_datetime', tzinfo=melb),
  509. ... ).values('hour').annotate(experiments=Count('id'))
  510. >>> for exp in experiments_per_hour:
  511. ... print(exp['hour'], exp['experiments'])
  512. ...
  513. 2014-06-16 00:00:00+10:00 2
  514. 2016-01-01 04:00:00+11:00 1
  515. .. _text-functions:
  516. Text functions
  517. ==============
  518. ``Concat``
  519. ----------
  520. .. class:: Concat(*expressions, **extra)
  521. Accepts a list of at least two text fields or expressions and returns the
  522. concatenated text. Each argument must be of a text or char type. If you want
  523. to concatenate a ``TextField()`` with a ``CharField()``, then be sure to tell
  524. Django that the ``output_field`` should be a ``TextField()``. Specifying an
  525. ``output_field`` is also required when concatenating a ``Value`` as in the
  526. example below.
  527. This function will never have a null result. On backends where a null argument
  528. results in the entire expression being null, Django will ensure that each null
  529. part is converted to an empty string first.
  530. Usage example::
  531. >>> # Get the display name as "name (goes_by)"
  532. >>> from django.db.models import CharField, Value as V
  533. >>> from django.db.models.functions import Concat
  534. >>> Author.objects.create(name='Margaret Smith', goes_by='Maggie')
  535. >>> author = Author.objects.annotate(
  536. ... screen_name=Concat(
  537. ... 'name', V(' ('), 'goes_by', V(')'),
  538. ... output_field=CharField()
  539. ... )
  540. ... ).get()
  541. >>> print(author.screen_name)
  542. Margaret Smith (Maggie)
  543. ``Length``
  544. ----------
  545. .. class:: Length(expression, **extra)
  546. Accepts a single text field or expression and returns the number of characters
  547. the value has. If the expression is null, then the length will also be null.
  548. Usage example::
  549. >>> # Get the length of the name and goes_by fields
  550. >>> from django.db.models.functions import Length
  551. >>> Author.objects.create(name='Margaret Smith')
  552. >>> author = Author.objects.annotate(
  553. ... name_length=Length('name'),
  554. ... goes_by_length=Length('goes_by')).get()
  555. >>> print(author.name_length, author.goes_by_length)
  556. (14, None)
  557. It can also be registered as a transform. For example::
  558. >>> from django.db.models import CharField
  559. >>> from django.db.models.functions import Length
  560. >>> CharField.register_lookup(Length, 'length')
  561. >>> # Get authors whose name is longer than 7 characters
  562. >>> authors = Author.objects.filter(name__length__gt=7)
  563. ``Lower``
  564. ---------
  565. .. class:: Lower(expression, **extra)
  566. Accepts a single text field or expression and returns the lowercase
  567. representation.
  568. It can also be registered as a transform as described in :class:`Length`.
  569. Usage example::
  570. >>> from django.db.models.functions import Lower
  571. >>> Author.objects.create(name='Margaret Smith')
  572. >>> author = Author.objects.annotate(name_lower=Lower('name')).get()
  573. >>> print(author.name_lower)
  574. margaret smith
  575. ``Replace``
  576. ~~~~~~~~~~~
  577. .. class:: Replace(expression, text, replacement=Value(''), **extra)
  578. .. versionadded:: 2.1
  579. Replaces all occurrences of ``text`` with ``replacement`` in ``expression``.
  580. The default replacement text is the empty string. The arguments to the function
  581. are case-sensitive.
  582. Usage example::
  583. >>> from django.db.models import Value
  584. >>> from django.db.models.functions import Replace
  585. >>> Author.objects.create(name='Margaret Johnson')
  586. >>> Author.objects.create(name='Margaret Smith')
  587. >>> Author.objects.update(name=Replace('name', Value('Margaret'), Value('Margareth')))
  588. 2
  589. >>> Author.objects.values('name')
  590. <QuerySet [{'name': 'Margareth Johnson'}, {'name': 'Margareth Smith'}]>
  591. ``StrIndex``
  592. ------------
  593. .. class:: StrIndex(string, substring, **extra)
  594. .. versionadded:: 2.0
  595. Returns a positive integer corresponding to the 1-indexed position of the first
  596. occurrence of ``substring`` inside ``string``, or 0 if ``substring`` is not
  597. found.
  598. Usage example::
  599. >>> from django.db.models import Value as V
  600. >>> from django.db.models.functions import StrIndex
  601. >>> Author.objects.create(name='Margaret Smith')
  602. >>> Author.objects.create(name='Smith, Margaret')
  603. >>> Author.objects.create(name='Margaret Jackson')
  604. >>> Author.objects.filter(name='Margaret Jackson').annotate(
  605. ... smith_index=StrIndex('name', V('Smith'))
  606. ... ).get().smith_index
  607. 0
  608. >>> authors = Author.objects.annotate(
  609. ... smith_index=StrIndex('name', V('Smith'))
  610. ... ).filter(smith_index__gt=0)
  611. <QuerySet [<Author: Margaret Smith>, <Author: Smith, Margaret>]>
  612. .. warning::
  613. In MySQL, a database table's :ref:`collation<mysql-collation>` determines
  614. whether string comparisons (such as the ``expression`` and ``substring`` of
  615. this function) are case-sensitive. Comparisons are case-insensitive by
  616. default.
  617. ``Substr``
  618. ----------
  619. .. class:: Substr(expression, pos, length=None, **extra)
  620. Returns a substring of length ``length`` from the field or expression starting
  621. at position ``pos``. The position is 1-indexed, so the position must be greater
  622. than 0. If ``length`` is ``None``, then the rest of the string will be returned.
  623. Usage example::
  624. >>> # Set the alias to the first 5 characters of the name as lowercase
  625. >>> from django.db.models.functions import Substr, Lower
  626. >>> Author.objects.create(name='Margaret Smith')
  627. >>> Author.objects.update(alias=Lower(Substr('name', 1, 5)))
  628. 1
  629. >>> print(Author.objects.get(name='Margaret Smith').alias)
  630. marga
  631. ``Upper``
  632. ---------
  633. .. class:: Upper(expression, **extra)
  634. Accepts a single text field or expression and returns the uppercase
  635. representation.
  636. It can also be registered as a transform as described in :class:`Length`.
  637. Usage example::
  638. >>> from django.db.models.functions import Upper
  639. >>> Author.objects.create(name='Margaret Smith')
  640. >>> author = Author.objects.annotate(name_upper=Upper('name')).get()
  641. >>> print(author.name_upper)
  642. MARGARET SMITH
  643. .. _window-functions:
  644. Window functions
  645. ================
  646. .. versionadded:: 2.0
  647. There are a number of functions to use in a
  648. :class:`~django.db.models.expressions.Window` expression for computing the rank
  649. of elements or the :class:`Ntile` of some rows.
  650. ``CumeDist``
  651. ------------
  652. .. class:: CumeDist(*expressions, **extra)
  653. Calculates the cumulative distribution of a value within a window or partition.
  654. The cumulative distribution is defined as the number of rows preceding or
  655. peered with the current row divided by the total number of rows in the frame.
  656. ``DenseRank``
  657. -------------
  658. .. class:: DenseRank(*expressions, **extra)
  659. Equivalent to :class:`Rank` but does not have gaps.
  660. ``FirstValue``
  661. --------------
  662. .. class:: FirstValue(expression, **extra)
  663. Returns the value evaluated at the row that's the first row of the window
  664. frame, or ``None`` if no such value exists.
  665. ``Lag``
  666. -------
  667. .. class:: Lag(expression, offset=1, default=None, **extra)
  668. Calculates the value offset by ``offset``, and if no row exists there, returns
  669. ``default``.
  670. ``default`` must have the same type as the ``expression``, however, this is
  671. only validated by the database and not in Python.
  672. ``LastValue``
  673. -------------
  674. .. class:: LastValue(expression, **extra)
  675. Comparable to :class:`FirstValue`, it calculates the last value in a given
  676. frame clause.
  677. ``Lead``
  678. --------
  679. .. class:: Lead(expression, offset=1, default=None, **extra)
  680. Calculates the leading value in a given :ref:`frame <window-frames>`. Both
  681. ``offset`` and ``default`` are evaluated with respect to the current row.
  682. ``default`` must have the same type as the ``expression``, however, this is
  683. only validated by the database and not in Python.
  684. ``NthValue``
  685. ------------
  686. .. class:: NthValue(expression, nth=1, **extra)
  687. Computes the row relative to the offset ``nth`` (must be a positive value)
  688. within the window. Returns ``None`` if no row exists.
  689. Some databases may handle a nonexistent nth-value differently. For example,
  690. Oracle returns an empty string rather than ``None`` for character-based
  691. expressions. Django doesn't do any conversions in these cases.
  692. ``Ntile``
  693. ---------
  694. .. class:: Ntile(num_buckets=1, **extra)
  695. Calculates a partition for each of the rows in the frame clause, distributing
  696. numbers as evenly as possible between 1 and ``num_buckets``. If the rows don't
  697. divide evenly into a number of buckets, one or more buckets will be represented
  698. more frequently.
  699. ``PercentRank``
  700. ---------------
  701. .. class:: PercentRank(*expressions, **extra)
  702. Computes the percentile rank of the rows in the frame clause. This
  703. computation is equivalent to evaluating::
  704. (rank - 1) / (total rows - 1)
  705. The following table explains the calculation for the percentile rank of a row:
  706. ===== ===== ==== ============ ============
  707. Row # Value Rank Calculation Percent Rank
  708. ===== ===== ==== ============ ============
  709. 1 15 1 (1-1)/(7-1) 0.0000
  710. 2 20 2 (2-1)/(7-1) 0.1666
  711. 3 20 2 (2-1)/(7-1) 0.1666
  712. 4 20 2 (2-1)/(7-1) 0.1666
  713. 5 30 5 (5-1)/(7-1) 0.6666
  714. 6 30 5 (5-1)/(7-1) 0.6666
  715. 7 40 7 (7-1)/(7-1) 1.0000
  716. ===== ===== ==== ============ ============
  717. ``Rank``
  718. --------
  719. .. class:: Rank(*expressions, **extra)
  720. Comparable to ``RowNumber``, this function ranks rows in the window. The
  721. computed rank contains gaps. Use :class:`DenseRank` to compute rank without
  722. gaps.
  723. ``RowNumber``
  724. -------------
  725. .. class:: RowNumber(*expressions, **extra)
  726. Computes the row number according to the ordering of either the frame clause
  727. or the ordering of the whole query if there is no partitioning of the
  728. :ref:`window frame <window-frames>`.