2
0

fields.txt 31 KB

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