database-functions.txt 56 KB

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