fields.txt 31 KB

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