database-functions.txt 58 KB

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