fields.txt 29 KB

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