database-functions.txt 57 KB

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