database-functions.txt 58 KB

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