fields.txt 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. ================================
  2. PostgreSQL specific model fields
  3. ================================
  4. All of these fields are available from the ``django.contrib.postgres.fields``
  5. module.
  6. .. currentmodule:: django.contrib.postgres.fields
  7. Indexing these fields
  8. =====================
  9. :class:`~django.db.models.Index` and :attr:`.Field.db_index` both create a
  10. B-tree index, which isn't particularly helpful when querying complex data types.
  11. Indexes such as :class:`~django.contrib.postgres.indexes.GinIndex` and
  12. :class:`~django.contrib.postgres.indexes.GistIndex` are better suited, though
  13. the index choice is dependent on the queries that you're using. Generally, GiST
  14. may be a good choice for the :ref:`range fields <range-fields>` and
  15. :class:`HStoreField`, and GIN may be helpful for :class:`ArrayField`.
  16. ``ArrayField``
  17. ==============
  18. .. class:: ArrayField(base_field, size=None, **options)
  19. A field for storing lists of data. Most field types can be used, and you
  20. pass another field instance as the :attr:`base_field
  21. <ArrayField.base_field>`. You may also specify a :attr:`size
  22. <ArrayField.size>`. ``ArrayField`` can be nested to store multi-dimensional
  23. arrays.
  24. If you give the field a :attr:`~django.db.models.Field.default`, ensure
  25. it's a callable such as ``list`` (for an empty default) or a callable that
  26. returns a list (such as a function). Incorrectly using ``default=[]``
  27. creates a mutable default that is shared between all instances of
  28. ``ArrayField``.
  29. .. attribute:: base_field
  30. This is a required argument.
  31. Specifies the underlying data type and behavior for the array. It
  32. should be an instance of a subclass of
  33. :class:`~django.db.models.Field`. For example, it could be an
  34. :class:`~django.db.models.IntegerField` or a
  35. :class:`~django.db.models.CharField`. Most field types are permitted,
  36. with the exception of those handling relational data
  37. (:class:`~django.db.models.ForeignKey`,
  38. :class:`~django.db.models.OneToOneField` and
  39. :class:`~django.db.models.ManyToManyField`) and file fields (
  40. :class:`~django.db.models.FileField` and
  41. :class:`~django.db.models.ImageField`).
  42. It is possible to nest array fields - you can specify an instance of
  43. ``ArrayField`` as the ``base_field``. For example::
  44. from django.contrib.postgres.fields import ArrayField
  45. from django.db import models
  46. class ChessBoard(models.Model):
  47. board = ArrayField(
  48. ArrayField(
  49. models.CharField(max_length=10, blank=True),
  50. size=8,
  51. ),
  52. size=8,
  53. )
  54. Transformation of values between the database and the model, validation
  55. of data and configuration, and serialization are all delegated to the
  56. underlying base field.
  57. .. attribute:: size
  58. This is an optional argument.
  59. If passed, the array will have a maximum size as specified. This will
  60. be passed to the database, although PostgreSQL at present does not
  61. enforce the restriction.
  62. .. note::
  63. When nesting ``ArrayField``, whether you use the ``size`` parameter or not,
  64. PostgreSQL requires that the arrays are rectangular::
  65. from django.contrib.postgres.fields import ArrayField
  66. from django.db import models
  67. class Board(models.Model):
  68. pieces = ArrayField(ArrayField(models.IntegerField()))
  69. # Valid
  70. Board(pieces=[
  71. [2, 3],
  72. [2, 1],
  73. ])
  74. # Not valid
  75. Board(pieces=[
  76. [2, 3],
  77. [2],
  78. ])
  79. If irregular shapes are required, then the underlying field should be made
  80. nullable and the values padded with ``None``.
  81. Querying ``ArrayField``
  82. -----------------------
  83. There are a number of custom lookups and transforms for :class:`ArrayField`.
  84. We will use the following example model::
  85. from django.contrib.postgres.fields import ArrayField
  86. from django.db import models
  87. class Post(models.Model):
  88. name = models.CharField(max_length=200)
  89. tags = ArrayField(models.CharField(max_length=200), blank=True)
  90. def __str__(self):
  91. return self.name
  92. .. fieldlookup:: arrayfield.contains
  93. ``contains``
  94. ~~~~~~~~~~~~
  95. The :lookup:`contains` lookup is overridden on :class:`ArrayField`. The
  96. returned objects will be those where the values passed are a subset of the
  97. data. It uses the SQL operator ``@>``. For example::
  98. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  99. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  100. >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
  101. >>> Post.objects.filter(tags__contains=['thoughts'])
  102. <QuerySet [<Post: First post>, <Post: Second post>]>
  103. >>> Post.objects.filter(tags__contains=['django'])
  104. <QuerySet [<Post: First post>, <Post: Third post>]>
  105. >>> Post.objects.filter(tags__contains=['django', 'thoughts'])
  106. <QuerySet [<Post: First post>]>
  107. .. fieldlookup:: arrayfield.contained_by
  108. ``contained_by``
  109. ~~~~~~~~~~~~~~~~
  110. This is the inverse of the :lookup:`contains <arrayfield.contains>` lookup -
  111. the objects returned will be those where the data is a subset of the values
  112. passed. It uses the SQL operator ``<@``. For example::
  113. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  114. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  115. >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
  116. >>> Post.objects.filter(tags__contained_by=['thoughts', 'django'])
  117. <QuerySet [<Post: First post>, <Post: Second post>]>
  118. >>> Post.objects.filter(tags__contained_by=['thoughts', 'django', 'tutorial'])
  119. <QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
  120. .. fieldlookup:: arrayfield.overlap
  121. ``overlap``
  122. ~~~~~~~~~~~
  123. Returns objects where the data shares any results with the values passed. Uses
  124. the SQL operator ``&&``. For example::
  125. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  126. >>> Post.objects.create(name='Second post', tags=['thoughts', 'tutorial'])
  127. >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
  128. >>> Post.objects.filter(tags__overlap=['thoughts'])
  129. <QuerySet [<Post: First post>, <Post: Second post>]>
  130. >>> Post.objects.filter(tags__overlap=['thoughts', 'tutorial'])
  131. <QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
  132. >>> Post.objects.filter(tags__overlap=Post.objects.values_list('tags'))
  133. <QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
  134. .. versionchanged:: 4.2
  135. Support for ``QuerySet.values()`` and ``values_list()`` as a right-hand
  136. side was added.
  137. .. fieldlookup:: arrayfield.len
  138. ``len``
  139. ~~~~~~~
  140. Returns the length of the array. The lookups available afterward are those
  141. available for :class:`~django.db.models.IntegerField`. For example::
  142. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  143. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  144. >>> Post.objects.filter(tags__len=1)
  145. <QuerySet [<Post: Second post>]>
  146. .. fieldlookup:: arrayfield.index
  147. Index transforms
  148. ~~~~~~~~~~~~~~~~
  149. Index transforms index into the array. Any non-negative integer can be used.
  150. There are no errors if it exceeds the :attr:`size <ArrayField.size>` of the
  151. array. The lookups available after the transform are those from the
  152. :attr:`base_field <ArrayField.base_field>`. For example::
  153. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  154. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  155. >>> Post.objects.filter(tags__0='thoughts')
  156. <QuerySet [<Post: First post>, <Post: Second post>]>
  157. >>> Post.objects.filter(tags__1__iexact='Django')
  158. <QuerySet [<Post: First post>]>
  159. >>> Post.objects.filter(tags__276='javascript')
  160. <QuerySet []>
  161. .. note::
  162. PostgreSQL uses 1-based indexing for array fields when writing raw SQL.
  163. However these indexes and those used in :lookup:`slices <arrayfield.slice>`
  164. use 0-based indexing to be consistent with Python.
  165. .. fieldlookup:: arrayfield.slice
  166. Slice transforms
  167. ~~~~~~~~~~~~~~~~
  168. Slice transforms take a slice of the array. Any two non-negative integers can
  169. be used, separated by a single underscore. The lookups available after the
  170. transform do not change. For example::
  171. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  172. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  173. >>> Post.objects.create(name='Third post', tags=['django', 'python', 'thoughts'])
  174. >>> Post.objects.filter(tags__0_1=['thoughts'])
  175. <QuerySet [<Post: First post>, <Post: Second post>]>
  176. >>> Post.objects.filter(tags__0_2__contains=['thoughts'])
  177. <QuerySet [<Post: First post>, <Post: Second post>]>
  178. .. note::
  179. PostgreSQL uses 1-based indexing for array fields when writing raw SQL.
  180. However these slices and those used in :lookup:`indexes <arrayfield.index>`
  181. use 0-based indexing to be consistent with Python.
  182. .. admonition:: Multidimensional arrays with indexes and slices
  183. PostgreSQL has some rather esoteric behavior when using indexes and slices
  184. on multidimensional arrays. It will always work to use indexes to reach
  185. down to the final underlying data, but most other slices behave strangely
  186. at the database level and cannot be supported in a logical, consistent
  187. fashion by Django.
  188. ``CIText`` fields
  189. =================
  190. .. class:: CIText(**options)
  191. .. deprecated:: 4.2
  192. A mixin to create case-insensitive text fields backed by the citext_ type.
  193. Read about `the performance considerations`_ prior to using it.
  194. To use ``citext``, use the :class:`.CITextExtension` operation to
  195. :ref:`set up the citext extension <create-postgresql-extensions>` in
  196. PostgreSQL before the first ``CreateModel`` migration operation.
  197. If you're using an :class:`~django.contrib.postgres.fields.ArrayField`
  198. of ``CIText`` fields, you must add ``'django.contrib.postgres'`` in your
  199. :setting:`INSTALLED_APPS`, otherwise field values will appear as strings
  200. like ``'{thoughts,django}'``.
  201. Several fields that use the mixin are provided:
  202. .. class:: CICharField(**options)
  203. .. deprecated:: 4.2
  204. ``CICharField`` is deprecated in favor of
  205. ``CharField(db_collation="…")`` with a case-insensitive
  206. non-deterministic collation.
  207. .. class:: CIEmailField(**options)
  208. .. deprecated:: 4.2
  209. ``CIEmailField`` is deprecated in favor of
  210. ``EmailField(db_collation="…")`` with a case-insensitive
  211. non-deterministic collation.
  212. .. class:: CITextField(**options)
  213. .. deprecated:: 4.2
  214. ``CITextField`` is deprecated in favor of
  215. ``TextField(db_collation="…")`` with a case-insensitive
  216. non-deterministic collation.
  217. These fields subclass :class:`~django.db.models.CharField`,
  218. :class:`~django.db.models.EmailField`, and
  219. :class:`~django.db.models.TextField`, respectively.
  220. ``max_length`` won't be enforced in the database since ``citext`` behaves
  221. similar to PostgreSQL's ``text`` type.
  222. .. _citext: https://www.postgresql.org/docs/current/citext.html
  223. .. _the performance considerations: https://www.postgresql.org/docs/current/citext.html#id-1.11.7.19.9
  224. .. admonition:: Case-insensitive collations
  225. It's preferable to use non-deterministic collations instead of the
  226. ``citext`` extension. You can create them using the
  227. :class:`~django.contrib.postgres.operations.CreateCollation` migration
  228. operation. For more details, see :ref:`manage-postgresql-collations` and
  229. the PostgreSQL documentation about `non-deterministic collations`_.
  230. .. _non-deterministic collations: https://www.postgresql.org/docs/current/collation.html#COLLATION-NONDETERMINISTIC
  231. ``HStoreField``
  232. ===============
  233. .. class:: HStoreField(**options)
  234. A field for storing key-value pairs. The Python data type used is a
  235. ``dict``. Keys must be strings, and values may be either strings or nulls
  236. (``None`` in Python).
  237. To use this field, you'll need to:
  238. #. Add ``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS`.
  239. #. :ref:`Set up the hstore extension <create-postgresql-extensions>` in
  240. PostgreSQL.
  241. You'll see an error like ``can't adapt type 'dict'`` if you skip the first
  242. step, or ``type "hstore" does not exist`` if you skip the second.
  243. .. note::
  244. On occasions it may be useful to require or restrict the keys which are
  245. valid for a given field. This can be done using the
  246. :class:`~django.contrib.postgres.validators.KeysValidator`.
  247. Querying ``HStoreField``
  248. ------------------------
  249. In addition to the ability to query by key, there are a number of custom
  250. lookups available for ``HStoreField``.
  251. We will use the following example model::
  252. from django.contrib.postgres.fields import HStoreField
  253. from django.db import models
  254. class Dog(models.Model):
  255. name = models.CharField(max_length=200)
  256. data = HStoreField()
  257. def __str__(self):
  258. return self.name
  259. .. fieldlookup:: hstorefield.key
  260. Key lookups
  261. ~~~~~~~~~~~
  262. To query based on a given key, you can use that key as the lookup name::
  263. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  264. >>> Dog.objects.create(name='Meg', data={'breed': 'collie'})
  265. >>> Dog.objects.filter(data__breed='collie')
  266. <QuerySet [<Dog: Meg>]>
  267. You can chain other lookups after key lookups::
  268. >>> Dog.objects.filter(data__breed__contains='l')
  269. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
  270. or use ``F()`` expressions to annotate a key value. For example::
  271. >>> from django.db.models import F
  272. >>> rufus = Dog.objects.annotate(breed=F("data__breed"))[0]
  273. >>> rufus.breed
  274. 'labrador'
  275. If the key you wish to query by clashes with the name of another lookup, you
  276. need to use the :lookup:`hstorefield.contains` lookup instead.
  277. .. note::
  278. Key transforms can also be chained with: :lookup:`contains`,
  279. :lookup:`icontains`, :lookup:`endswith`, :lookup:`iendswith`,
  280. :lookup:`iexact`, :lookup:`regex`, :lookup:`iregex`, :lookup:`startswith`,
  281. and :lookup:`istartswith` lookups.
  282. .. warning::
  283. Since any string could be a key in a hstore value, any lookup other than
  284. those listed below will be interpreted as a key lookup. No errors are
  285. raised. Be extra careful for typing mistakes, and always check your queries
  286. work as you intend.
  287. .. fieldlookup:: hstorefield.contains
  288. ``contains``
  289. ~~~~~~~~~~~~
  290. The :lookup:`contains` lookup is overridden on
  291. :class:`~django.contrib.postgres.fields.HStoreField`. The returned objects are
  292. those where the given ``dict`` of key-value pairs are all contained in the
  293. field. It uses the SQL operator ``@>``. For example::
  294. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
  295. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  296. >>> Dog.objects.create(name='Fred', data={})
  297. >>> Dog.objects.filter(data__contains={'owner': 'Bob'})
  298. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
  299. >>> Dog.objects.filter(data__contains={'breed': 'collie'})
  300. <QuerySet [<Dog: Meg>]>
  301. .. fieldlookup:: hstorefield.contained_by
  302. ``contained_by``
  303. ~~~~~~~~~~~~~~~~
  304. This is the inverse of the :lookup:`contains <hstorefield.contains>` lookup -
  305. the objects returned will be those where the key-value pairs on the object are
  306. a subset of those in the value passed. It uses the SQL operator ``<@``. For
  307. example::
  308. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
  309. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  310. >>> Dog.objects.create(name='Fred', data={})
  311. >>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'})
  312. <QuerySet [<Dog: Meg>, <Dog: Fred>]>
  313. >>> Dog.objects.filter(data__contained_by={'breed': 'collie'})
  314. <QuerySet [<Dog: Fred>]>
  315. .. fieldlookup:: hstorefield.has_key
  316. ``has_key``
  317. ~~~~~~~~~~~
  318. Returns objects where the given key is in the data. Uses the SQL operator
  319. ``?``. For example::
  320. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  321. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  322. >>> Dog.objects.filter(data__has_key='owner')
  323. <QuerySet [<Dog: Meg>]>
  324. .. fieldlookup:: hstorefield.has_any_keys
  325. ``has_any_keys``
  326. ~~~~~~~~~~~~~~~~
  327. Returns objects where any of the given keys are in the data. Uses the SQL
  328. operator ``?|``. For example::
  329. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  330. >>> Dog.objects.create(name='Meg', data={'owner': 'Bob'})
  331. >>> Dog.objects.create(name='Fred', data={})
  332. >>> Dog.objects.filter(data__has_any_keys=['owner', 'breed'])
  333. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
  334. .. fieldlookup:: hstorefield.has_keys
  335. ``has_keys``
  336. ~~~~~~~~~~~~
  337. Returns objects where all of the given keys are in the data. Uses the SQL operator
  338. ``?&``. For example::
  339. >>> Dog.objects.create(name='Rufus', data={})
  340. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  341. >>> Dog.objects.filter(data__has_keys=['breed', 'owner'])
  342. <QuerySet [<Dog: Meg>]>
  343. .. fieldlookup:: hstorefield.keys
  344. ``keys``
  345. ~~~~~~~~
  346. Returns objects where the array of keys is the given value. Note that the order
  347. is not guaranteed to be reliable, so this transform is mainly useful for using
  348. in conjunction with lookups on
  349. :class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function
  350. ``akeys()``. For example::
  351. >>> Dog.objects.create(name='Rufus', data={'toy': 'bone'})
  352. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  353. >>> Dog.objects.filter(data__keys__overlap=['breed', 'toy'])
  354. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
  355. .. fieldlookup:: hstorefield.values
  356. ``values``
  357. ~~~~~~~~~~
  358. Returns objects where the array of values is the given value. Note that the
  359. order is not guaranteed to be reliable, so this transform is mainly useful for
  360. using in conjunction with lookups on
  361. :class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function
  362. ``avals()``. For example::
  363. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  364. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  365. >>> Dog.objects.filter(data__values__contains=['collie'])
  366. <QuerySet [<Dog: Meg>]>
  367. .. _range-fields:
  368. Range Fields
  369. ============
  370. There are five range field types, corresponding to the built-in range types in
  371. PostgreSQL. These fields are used to store a range of values; for example the
  372. start and end timestamps of an event, or the range of ages an activity is
  373. suitable for.
  374. All of the range fields translate to :ref:`psycopg Range objects
  375. <psycopg:adapt-range>` in Python, but also accept tuples as input if no bounds
  376. information is necessary. The default is lower bound included, upper bound
  377. excluded, that is ``[)`` (see the PostgreSQL documentation for details about
  378. `different bounds`_). The default bounds can be changed for non-discrete range
  379. fields (:class:`.DateTimeRangeField` and :class:`.DecimalRangeField`) by using
  380. the ``default_bounds`` argument.
  381. ``IntegerRangeField``
  382. ---------------------
  383. .. class:: IntegerRangeField(**options)
  384. Stores a range of integers. Based on an
  385. :class:`~django.db.models.IntegerField`. Represented by an ``int4range`` in
  386. the database and a
  387. ``django.db.backends.postgresql.psycopg_any.NumericRange`` in Python.
  388. Regardless of the bounds specified when saving the data, PostgreSQL always
  389. returns a range in a canonical form that includes the lower bound and
  390. excludes the upper bound, that is ``[)``.
  391. ``BigIntegerRangeField``
  392. ------------------------
  393. .. class:: BigIntegerRangeField(**options)
  394. Stores a range of large integers. Based on a
  395. :class:`~django.db.models.BigIntegerField`. Represented by an ``int8range``
  396. in the database and a
  397. ``django.db.backends.postgresql.psycopg_any.NumericRange`` in Python.
  398. Regardless of the bounds specified when saving the data, PostgreSQL always
  399. returns a range in a canonical form that includes the lower bound and
  400. excludes the upper bound, that is ``[)``.
  401. ``DecimalRangeField``
  402. ---------------------
  403. .. class:: DecimalRangeField(default_bounds='[)', **options)
  404. Stores a range of floating point values. Based on a
  405. :class:`~django.db.models.DecimalField`. Represented by a ``numrange`` in
  406. the database and a
  407. ``django.db.backends.postgresql.psycopg_any.NumericRange`` in Python.
  408. .. attribute:: DecimalRangeField.default_bounds
  409. .. versionadded:: 4.1
  410. Optional. The value of ``bounds`` for list and tuple inputs. The
  411. default is lower bound included, upper bound excluded, that is ``[)``
  412. (see the PostgreSQL documentation for details about
  413. `different bounds`_). ``default_bounds`` is not used for
  414. ``django.db.backends.postgresql.psycopg_any.NumericRange`` inputs.
  415. ``DateTimeRangeField``
  416. ----------------------
  417. .. class:: DateTimeRangeField(default_bounds='[)', **options)
  418. Stores a range of timestamps. Based on a
  419. :class:`~django.db.models.DateTimeField`. Represented by a ``tstzrange`` in
  420. the database and a
  421. ``django.db.backends.postgresql.psycopg_any.DateTimeTZRange`` in Python.
  422. .. attribute:: DateTimeRangeField.default_bounds
  423. .. versionadded:: 4.1
  424. Optional. The value of ``bounds`` for list and tuple inputs. The
  425. default is lower bound included, upper bound excluded, that is ``[)``
  426. (see the PostgreSQL documentation for details about
  427. `different bounds`_). ``default_bounds`` is not used for
  428. ``django.db.backends.postgresql.psycopg_any.DateTimeTZRange`` inputs.
  429. ``DateRangeField``
  430. ------------------
  431. .. class:: DateRangeField(**options)
  432. Stores a range of dates. Based on a
  433. :class:`~django.db.models.DateField`. Represented by a ``daterange`` in the
  434. database and a ``django.db.backends.postgresql.psycopg_any.DateRange`` in
  435. Python.
  436. Regardless of the bounds specified when saving the data, PostgreSQL always
  437. returns a range in a canonical form that includes the lower bound and
  438. excludes the upper bound, that is ``[)``.
  439. Querying Range Fields
  440. ---------------------
  441. There are a number of custom lookups and transforms for range fields. They are
  442. available on all the above fields, but we will use the following example
  443. model::
  444. from django.contrib.postgres.fields import IntegerRangeField
  445. from django.db import models
  446. class Event(models.Model):
  447. name = models.CharField(max_length=200)
  448. ages = IntegerRangeField()
  449. start = models.DateTimeField()
  450. def __str__(self):
  451. return self.name
  452. We will also use the following example objects::
  453. >>> import datetime
  454. >>> from django.utils import timezone
  455. >>> now = timezone.now()
  456. >>> Event.objects.create(name='Soft play', ages=(0, 10), start=now)
  457. >>> Event.objects.create(name='Pub trip', ages=(21, None), start=now - datetime.timedelta(days=1))
  458. and ``NumericRange``:
  459. >>> from django.db.backends.postgresql.psycopg_any import NumericRange
  460. Containment functions
  461. ~~~~~~~~~~~~~~~~~~~~~
  462. As with other PostgreSQL fields, there are three standard containment
  463. operators: ``contains``, ``contained_by`` and ``overlap``, using the SQL
  464. operators ``@>``, ``<@``, and ``&&`` respectively.
  465. .. fieldlookup:: rangefield.contains
  466. ``contains``
  467. ^^^^^^^^^^^^
  468. >>> Event.objects.filter(ages__contains=NumericRange(4, 5))
  469. <QuerySet [<Event: Soft play>]>
  470. .. fieldlookup:: rangefield.contained_by
  471. ``contained_by``
  472. ^^^^^^^^^^^^^^^^
  473. >>> Event.objects.filter(ages__contained_by=NumericRange(0, 15))
  474. <QuerySet [<Event: Soft play>]>
  475. The ``contained_by`` lookup is also available on the non-range field types:
  476. :class:`~django.db.models.SmallAutoField`,
  477. :class:`~django.db.models.AutoField`, :class:`~django.db.models.BigAutoField`,
  478. :class:`~django.db.models.SmallIntegerField`,
  479. :class:`~django.db.models.IntegerField`,
  480. :class:`~django.db.models.BigIntegerField`,
  481. :class:`~django.db.models.DecimalField`, :class:`~django.db.models.FloatField`,
  482. :class:`~django.db.models.DateField`, and
  483. :class:`~django.db.models.DateTimeField`. For example::
  484. >>> from django.db.backends.postgresql.psycopg_any import DateTimeTZRange
  485. >>> Event.objects.filter(
  486. ... start__contained_by=DateTimeTZRange(
  487. ... timezone.now() - datetime.timedelta(hours=1),
  488. ... timezone.now() + datetime.timedelta(hours=1),
  489. ... ),
  490. ... )
  491. <QuerySet [<Event: Soft play>]>
  492. .. fieldlookup:: rangefield.overlap
  493. ``overlap``
  494. ^^^^^^^^^^^
  495. >>> Event.objects.filter(ages__overlap=NumericRange(8, 12))
  496. <QuerySet [<Event: Soft play>]>
  497. Comparison functions
  498. ~~~~~~~~~~~~~~~~~~~~
  499. Range fields support the standard lookups: :lookup:`lt`, :lookup:`gt`,
  500. :lookup:`lte` and :lookup:`gte`. These are not particularly helpful - they
  501. compare the lower bounds first and then the upper bounds only if necessary.
  502. This is also the strategy used to order by a range field. It is better to use
  503. the specific range comparison operators.
  504. .. fieldlookup:: rangefield.fully_lt
  505. ``fully_lt``
  506. ^^^^^^^^^^^^
  507. The returned ranges are strictly less than the passed range. In other words,
  508. all the points in the returned range are less than all those in the passed
  509. range.
  510. >>> Event.objects.filter(ages__fully_lt=NumericRange(11, 15))
  511. <QuerySet [<Event: Soft play>]>
  512. .. fieldlookup:: rangefield.fully_gt
  513. ``fully_gt``
  514. ^^^^^^^^^^^^
  515. The returned ranges are strictly greater than the passed range. In other words,
  516. the all the points in the returned range are greater than all those in the
  517. passed range.
  518. >>> Event.objects.filter(ages__fully_gt=NumericRange(11, 15))
  519. <QuerySet [<Event: Pub trip>]>
  520. .. fieldlookup:: rangefield.not_lt
  521. ``not_lt``
  522. ^^^^^^^^^^
  523. The returned ranges do not contain any points less than the passed range, that
  524. is the lower bound of the returned range is at least the lower bound of the
  525. passed range.
  526. >>> Event.objects.filter(ages__not_lt=NumericRange(0, 15))
  527. <QuerySet [<Event: Soft play>, <Event: Pub trip>]>
  528. .. fieldlookup:: rangefield.not_gt
  529. ``not_gt``
  530. ^^^^^^^^^^
  531. The returned ranges do not contain any points greater than the passed range, that
  532. is the upper bound of the returned range is at most the upper bound of the
  533. passed range.
  534. >>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))
  535. <QuerySet [<Event: Soft play>]>
  536. .. fieldlookup:: rangefield.adjacent_to
  537. ``adjacent_to``
  538. ^^^^^^^^^^^^^^^
  539. The returned ranges share a bound with the passed range.
  540. >>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21))
  541. <QuerySet [<Event: Soft play>, <Event: Pub trip>]>
  542. Querying using the bounds
  543. ~~~~~~~~~~~~~~~~~~~~~~~~~
  544. Range fields support several extra lookups.
  545. .. fieldlookup:: rangefield.startswith
  546. ``startswith``
  547. ^^^^^^^^^^^^^^
  548. Returned objects have the given lower bound. Can be chained to valid lookups
  549. for the base field.
  550. >>> Event.objects.filter(ages__startswith=21)
  551. <QuerySet [<Event: Pub trip>]>
  552. .. fieldlookup:: rangefield.endswith
  553. ``endswith``
  554. ^^^^^^^^^^^^
  555. Returned objects have the given upper bound. Can be chained to valid lookups
  556. for the base field.
  557. >>> Event.objects.filter(ages__endswith=10)
  558. <QuerySet [<Event: Soft play>]>
  559. .. fieldlookup:: rangefield.isempty
  560. ``isempty``
  561. ^^^^^^^^^^^
  562. Returned objects are empty ranges. Can be chained to valid lookups for a
  563. :class:`~django.db.models.BooleanField`.
  564. >>> Event.objects.filter(ages__isempty=True)
  565. <QuerySet []>
  566. .. fieldlookup:: rangefield.lower_inc
  567. ``lower_inc``
  568. ^^^^^^^^^^^^^
  569. Returns objects that have inclusive or exclusive lower bounds, depending on the
  570. boolean value passed. Can be chained to valid lookups for a
  571. :class:`~django.db.models.BooleanField`.
  572. >>> Event.objects.filter(ages__lower_inc=True)
  573. <QuerySet [<Event: Soft play>, <Event: Pub trip>]>
  574. .. fieldlookup:: rangefield.lower_inf
  575. ``lower_inf``
  576. ^^^^^^^^^^^^^
  577. Returns objects that have unbounded (infinite) or bounded lower bound,
  578. depending on the boolean value passed. Can be chained to valid lookups for a
  579. :class:`~django.db.models.BooleanField`.
  580. >>> Event.objects.filter(ages__lower_inf=True)
  581. <QuerySet []>
  582. .. fieldlookup:: rangefield.upper_inc
  583. ``upper_inc``
  584. ^^^^^^^^^^^^^
  585. Returns objects that have inclusive or exclusive upper bounds, depending on the
  586. boolean value passed. Can be chained to valid lookups for a
  587. :class:`~django.db.models.BooleanField`.
  588. >>> Event.objects.filter(ages__upper_inc=True)
  589. <QuerySet []>
  590. .. fieldlookup:: rangefield.upper_inf
  591. ``upper_inf``
  592. ^^^^^^^^^^^^^
  593. Returns objects that have unbounded (infinite) or bounded upper bound,
  594. depending on the boolean value passed. Can be chained to valid lookups for a
  595. :class:`~django.db.models.BooleanField`.
  596. >>> Event.objects.filter(ages__upper_inf=True)
  597. <QuerySet [<Event: Pub trip>]>
  598. Defining your own range types
  599. -----------------------------
  600. PostgreSQL allows the definition of custom range types. Django's model and form
  601. field implementations use base classes below, and ``psycopg`` provides a
  602. :func:`~psycopg:psycopg.types.range.register_range` to allow use of custom
  603. range types.
  604. .. class:: RangeField(**options)
  605. Base class for model range fields.
  606. .. attribute:: base_field
  607. The model field class to use.
  608. .. attribute:: range_type
  609. The range type to use.
  610. .. attribute:: form_field
  611. The form field class to use. Should be a subclass of
  612. :class:`django.contrib.postgres.forms.BaseRangeField`.
  613. .. class:: django.contrib.postgres.forms.BaseRangeField
  614. Base class for form range fields.
  615. .. attribute:: base_field
  616. The form field to use.
  617. .. attribute:: range_type
  618. The range type to use.
  619. Range operators
  620. ---------------
  621. .. class:: RangeOperators
  622. PostgreSQL provides a set of SQL operators that can be used together with the
  623. range data types (see `the PostgreSQL documentation for the full details of
  624. range operators <https://www.postgresql.org/docs/current/
  625. functions-range.html#RANGE-OPERATORS-TABLE>`_). This class is meant as a
  626. convenient method to avoid typos. The operator names overlap with the names of
  627. corresponding lookups.
  628. .. code-block:: python
  629. class RangeOperators:
  630. EQUAL = '='
  631. NOT_EQUAL = '<>'
  632. CONTAINS = '@>'
  633. CONTAINED_BY = '<@'
  634. OVERLAPS = '&&'
  635. FULLY_LT = '<<'
  636. FULLY_GT = '>>'
  637. NOT_LT = '&>'
  638. NOT_GT = '&<'
  639. ADJACENT_TO = '-|-'
  640. RangeBoundary() expressions
  641. ---------------------------
  642. .. class:: RangeBoundary(inclusive_lower=True, inclusive_upper=False)
  643. .. attribute:: inclusive_lower
  644. If ``True`` (default), the lower bound is inclusive ``'['``, otherwise
  645. it's exclusive ``'('``.
  646. .. attribute:: inclusive_upper
  647. If ``False`` (default), the upper bound is exclusive ``')'``, otherwise
  648. it's inclusive ``']'``.
  649. A ``RangeBoundary()`` expression represents the range boundaries. It can be
  650. used with a custom range functions that expected boundaries, for example to
  651. define :class:`~django.contrib.postgres.constraints.ExclusionConstraint`. See
  652. `the PostgreSQL documentation for the full details <https://www.postgresql.org/
  653. docs/current/rangetypes.html#RANGETYPES-INCLUSIVITY>`_.
  654. .. _different bounds: https://www.postgresql.org/docs/current/rangetypes.html#RANGETYPES-IO