fields.txt 30 KB

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