fields.txt 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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. ``CIText`` fields
  180. =================
  181. .. class:: CIText(**options)
  182. .. versionadded:: 1.11
  183. A mixin to create case-insensitive text fields backed by the citext_ type.
  184. Read about `the performance considerations`_ prior to using it.
  185. To use ``citext``, use the :class:`.CITextExtension` operation to
  186. :ref:`setup the citext extension <create-postgresql-extensions>` in
  187. PostgreSQL before the first ``CreateModel`` migration operation.
  188. Several fields that use the mixin are provided:
  189. .. class:: CICharField(**options)
  190. .. class:: CIEmailField(**options)
  191. .. class:: CITextField(**options)
  192. These fields subclass :class:`~django.db.models.CharField`,
  193. :class:`~django.db.models.EmailField`, and
  194. :class:`~django.db.models.TextField`, respectively.
  195. ``max_length`` won't be enforced in the database since ``citext`` behaves
  196. similar to PostgreSQL's ``text`` type.
  197. .. _citext: https://www.postgresql.org/docs/current/static/citext.html
  198. .. _the performance considerations: https://www.postgresql.org/docs/current/static/citext.html#AEN169274
  199. ``HStoreField``
  200. ===============
  201. .. class:: HStoreField(**options)
  202. A field for storing key-value pairs. The Python data type used is a
  203. ``dict``. Keys must be strings, and values may be either strings or nulls
  204. (``None`` in Python).
  205. To use this field, you'll need to:
  206. 1. Add ``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS`.
  207. 2. :ref:`Setup the hstore extension <create-postgresql-extensions>` in
  208. PostgreSQL.
  209. You'll see an error like ``can't adapt type 'dict'`` if you skip the first
  210. step, or ``type "hstore" does not exist`` if you skip the second.
  211. .. versionchanged:: 1.11
  212. Added the ability to store nulls. Previously, they were cast to strings.
  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. .. versionadded:: 1.11
  335. An optional JSON-encoding class to serialize data types not supported
  336. by the standard JSON serializer (``datetime``, ``uuid``, etc.). For
  337. example, you can use the
  338. :class:`~django.core.serializers.json.DjangoJSONEncoder` class or any
  339. other :py:class:`json.JSONEncoder` subclass.
  340. When the value is retrieved from the database, it will be in the format
  341. chosen by the custom encoder (most often a string), so you'll need to
  342. take extra steps to convert the value back to the initial data type
  343. (:meth:`Model.from_db() <django.db.models.Model.from_db>` and
  344. :meth:`Field.from_db_value() <django.db.models.Field.from_db_value>`
  345. are two possible hooks for that purpose). Your deserialization may need
  346. to account for the fact that you can't be certain of the input type.
  347. For example, you run the risk of returning a ``datetime`` that was
  348. actually a string that just happened to be in the same format chosen
  349. for ``datetime``\s.
  350. If you give the field a :attr:`~django.db.models.Field.default`, ensure
  351. it's a callable such as ``dict`` (for an empty default) or a callable that
  352. returns a dict (such as a function). Incorrectly using ``default={}``
  353. creates a mutable default that is shared between all instances of
  354. ``JSONField``.
  355. .. note::
  356. PostgreSQL has two native JSON based data types: ``json`` and ``jsonb``.
  357. The main difference between them is how they are stored and how they can be
  358. queried. PostgreSQL's ``json`` field is stored as the original string
  359. representation of the JSON and must be decoded on the fly when queried
  360. based on keys. The ``jsonb`` field is stored based on the actual structure
  361. of the JSON which allows indexing. The trade-off is a small additional cost
  362. on writing to the ``jsonb`` field. ``JSONField`` uses ``jsonb``.
  363. **As a result, this field requires PostgreSQL ≥ 9.4**.
  364. Querying ``JSONField``
  365. ----------------------
  366. We will use the following example model::
  367. from django.contrib.postgres.fields import JSONField
  368. from django.db import models
  369. class Dog(models.Model):
  370. name = models.CharField(max_length=200)
  371. data = JSONField()
  372. def __str__(self):
  373. return self.name
  374. .. fieldlookup:: jsonfield.key
  375. Key, index, and path lookups
  376. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  377. To query based on a given dictionary key, simply use that key as the lookup
  378. name::
  379. >>> Dog.objects.create(name='Rufus', data={
  380. ... 'breed': 'labrador',
  381. ... 'owner': {
  382. ... 'name': 'Bob',
  383. ... 'other_pets': [{
  384. ... 'name': 'Fishy',
  385. ... }],
  386. ... },
  387. ... })
  388. >>> Dog.objects.create(name='Meg', data={'breed': 'collie'})
  389. >>> Dog.objects.filter(data__breed='collie')
  390. <QuerySet [<Dog: Meg>]>
  391. Multiple keys can be chained together to form a path lookup::
  392. >>> Dog.objects.filter(data__owner__name='Bob')
  393. <QuerySet [<QuerySet <Dog: Rufus>]>
  394. If the key is an integer, it will be interpreted as an index lookup in an
  395. array::
  396. >>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy')
  397. <QuerySet [<Dog: Rufus>]>
  398. If the key you wish to query by clashes with the name of another lookup, use
  399. the :lookup:`jsonfield.contains` lookup instead.
  400. If only one key or index is used, the SQL operator ``->`` is used. If multiple
  401. operators are used then the ``#>`` operator is used.
  402. .. warning::
  403. Since any string could be a key in a JSON object, any lookup other than
  404. those listed below will be interpreted as a key lookup. No errors are
  405. raised. Be extra careful for typing mistakes, and always check your queries
  406. work as you intend.
  407. Containment and key operations
  408. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  409. .. fieldlookup:: jsonfield.contains
  410. .. fieldlookup:: jsonfield.contained_by
  411. .. fieldlookup:: jsonfield.has_key
  412. .. fieldlookup:: jsonfield.has_any_keys
  413. .. fieldlookup:: jsonfield.has_keys
  414. :class:`~django.contrib.postgres.fields.JSONField` shares lookups relating to
  415. containment and keys with :class:`~django.contrib.postgres.fields.HStoreField`.
  416. - :lookup:`contains <hstorefield.contains>` (accepts any JSON rather than
  417. just a dictionary of strings)
  418. - :lookup:`contained_by <hstorefield.contained_by>` (accepts any JSON
  419. rather than just a dictionary of strings)
  420. - :lookup:`has_key <hstorefield.has_key>`
  421. - :lookup:`has_any_keys <hstorefield.has_any_keys>`
  422. - :lookup:`has_keys <hstorefield.has_keys>`
  423. .. _range-fields:
  424. Range Fields
  425. ============
  426. There are five range field types, corresponding to the built-in range types in
  427. PostgreSQL. These fields are used to store a range of values; for example the
  428. start and end timestamps of an event, or the range of ages an activity is
  429. suitable for.
  430. All of the range fields translate to :ref:`psycopg2 Range objects
  431. <psycopg2:adapt-range>` in python, but also accept tuples as input if no bounds
  432. information is necessary. The default is lower bound included, upper bound
  433. excluded; that is, ``[)``.
  434. ``IntegerRangeField``
  435. ---------------------
  436. .. class:: IntegerRangeField(**options)
  437. Stores a range of integers. Based on an
  438. :class:`~django.db.models.IntegerField`. Represented by an ``int4range`` in
  439. the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in
  440. Python.
  441. Regardless of the bounds specified when saving the data, PostgreSQL always
  442. returns a range in a canonical form that includes the lower bound and
  443. excludes the upper bound; that is ``[)``.
  444. ``BigIntegerRangeField``
  445. ------------------------
  446. .. class:: BigIntegerRangeField(**options)
  447. Stores a range of large integers. Based on a
  448. :class:`~django.db.models.BigIntegerField`. Represented by an ``int8range``
  449. in the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in
  450. Python.
  451. Regardless of the bounds specified when saving the data, PostgreSQL always
  452. returns a range in a canonical form that includes the lower bound and
  453. excludes the upper bound; that is ``[)``.
  454. ``FloatRangeField``
  455. -------------------
  456. .. class:: FloatRangeField(**options)
  457. Stores a range of floating point values. Based on a
  458. :class:`~django.db.models.FloatField`. Represented by a ``numrange`` in the
  459. database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in Python.
  460. ``DateTimeRangeField``
  461. ----------------------
  462. .. class:: DateTimeRangeField(**options)
  463. Stores a range of timestamps. Based on a
  464. :class:`~django.db.models.DateTimeField`. Represented by a ``tztsrange`` in
  465. the database and a :class:`~psycopg2:psycopg2.extras.DateTimeTZRange` in
  466. Python.
  467. ``DateRangeField``
  468. ------------------
  469. .. class:: DateRangeField(**options)
  470. Stores a range of dates. Based on a
  471. :class:`~django.db.models.DateField`. Represented by a ``daterange`` in the
  472. database and a :class:`~psycopg2:psycopg2.extras.DateRange` in Python.
  473. Regardless of the bounds specified when saving the data, PostgreSQL always
  474. returns a range in a canonical form that includes the lower bound and
  475. excludes the upper bound; that is ``[)``.
  476. Querying Range Fields
  477. ---------------------
  478. There are a number of custom lookups and transforms for range fields. They are
  479. available on all the above fields, but we will use the following example
  480. model::
  481. from django.contrib.postgres.fields import IntegerRangeField
  482. from django.db import models
  483. class Event(models.Model):
  484. name = models.CharField(max_length=200)
  485. ages = IntegerRangeField()
  486. start = models.DateTimeField()
  487. def __str__(self):
  488. return self.name
  489. We will also use the following example objects::
  490. >>> import datetime
  491. >>> from django.utils import timezone
  492. >>> now = timezone.now()
  493. >>> Event.objects.create(name='Soft play', ages=(0, 10), start=now)
  494. >>> Event.objects.create(name='Pub trip', ages=(21, None), start=now - datetime.timedelta(days=1))
  495. and ``NumericRange``:
  496. >>> from psycopg2.extras import NumericRange
  497. Containment functions
  498. ~~~~~~~~~~~~~~~~~~~~~
  499. As with other PostgreSQL fields, there are three standard containment
  500. operators: ``contains``, ``contained_by`` and ``overlap``, using the SQL
  501. operators ``@>``, ``<@``, and ``&&`` respectively.
  502. .. fieldlookup:: rangefield.contains
  503. ``contains``
  504. ^^^^^^^^^^^^
  505. >>> Event.objects.filter(ages__contains=NumericRange(4, 5))
  506. <QuerySet [<Event: Soft play>]>
  507. .. fieldlookup:: rangefield.contained_by
  508. ``contained_by``
  509. ^^^^^^^^^^^^^^^^
  510. >>> Event.objects.filter(ages__contained_by=NumericRange(0, 15))
  511. <QuerySet [<Event: Soft play>]>
  512. The ``contained_by`` lookup is also available on the non-range field types:
  513. :class:`~django.db.models.IntegerField`,
  514. :class:`~django.db.models.BigIntegerField`,
  515. :class:`~django.db.models.FloatField`, :class:`~django.db.models.DateField`,
  516. and :class:`~django.db.models.DateTimeField`. For example::
  517. >>> from psycopg2.extras import DateTimeTZRange
  518. >>> Event.objects.filter(start__contained_by=DateTimeTZRange(
  519. ... timezone.now() - datetime.timedelta(hours=1),
  520. ... timezone.now() + datetime.timedelta(hours=1),
  521. ... )
  522. <QuerySet [<Event: Soft play>]>
  523. .. fieldlookup:: rangefield.overlap
  524. ``overlap``
  525. ^^^^^^^^^^^
  526. >>> Event.objects.filter(ages__overlap=NumericRange(8, 12))
  527. <QuerySet [<Event: Soft play>]>
  528. Comparison functions
  529. ~~~~~~~~~~~~~~~~~~~~
  530. Range fields support the standard lookups: :lookup:`lt`, :lookup:`gt`,
  531. :lookup:`lte` and :lookup:`gte`. These are not particularly helpful - they
  532. compare the lower bounds first and then the upper bounds only if necessary.
  533. This is also the strategy used to order by a range field. It is better to use
  534. the specific range comparison operators.
  535. .. fieldlookup:: rangefield.fully_lt
  536. ``fully_lt``
  537. ^^^^^^^^^^^^
  538. The returned ranges are strictly less than the passed range. In other words,
  539. all the points in the returned range are less than all those in the passed
  540. range.
  541. >>> Event.objects.filter(ages__fully_lt=NumericRange(11, 15))
  542. <QuerySet [<Event: Soft play>]>
  543. .. fieldlookup:: rangefield.fully_gt
  544. ``fully_gt``
  545. ^^^^^^^^^^^^
  546. The returned ranges are strictly greater than the passed range. In other words,
  547. the all the points in the returned range are greater than all those in the
  548. passed range.
  549. >>> Event.objects.filter(ages__fully_gt=NumericRange(11, 15))
  550. <QuerySet [<Event: Pub trip>]>
  551. .. fieldlookup:: rangefield.not_lt
  552. ``not_lt``
  553. ^^^^^^^^^^
  554. The returned ranges do not contain any points less than the passed range, that
  555. is the lower bound of the returned range is at least the lower bound of the
  556. passed range.
  557. >>> Event.objects.filter(ages__not_lt=NumericRange(0, 15))
  558. <QuerySet [<Event: Soft play>, <Event: Pub trip>]>
  559. .. fieldlookup:: rangefield.not_gt
  560. ``not_gt``
  561. ^^^^^^^^^^
  562. The returned ranges do not contain any points greater than the passed range, that
  563. is the upper bound of the returned range is at most the upper bound of the
  564. passed range.
  565. >>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))
  566. <QuerySet [<Event: Soft play>]>
  567. .. fieldlookup:: rangefield.adjacent_to
  568. ``adjacent_to``
  569. ^^^^^^^^^^^^^^^
  570. The returned ranges share a bound with the passed range.
  571. >>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21))
  572. <QuerySet [<Event: Soft play>, <Event: Pub trip>]>
  573. Querying using the bounds
  574. ~~~~~~~~~~~~~~~~~~~~~~~~~
  575. There are three transforms available for use in queries. You can extract the
  576. lower or upper bound, or query based on emptiness.
  577. .. fieldlookup:: rangefield.startswith
  578. ``startswith``
  579. ^^^^^^^^^^^^^^
  580. Returned objects have the given lower bound. Can be chained to valid lookups
  581. for the base field.
  582. >>> Event.objects.filter(ages__startswith=21)
  583. <QuerySet [<Event: Pub trip>]>
  584. .. fieldlookup:: rangefield.endswith
  585. ``endswith``
  586. ^^^^^^^^^^^^
  587. Returned objects have the given upper bound. Can be chained to valid lookups
  588. for the base field.
  589. >>> Event.objects.filter(ages__endswith=10)
  590. <QuerySet [<Event: Soft play>]>
  591. .. fieldlookup:: rangefield.isempty
  592. ``isempty``
  593. ^^^^^^^^^^^
  594. Returned objects are empty ranges. Can be chained to valid lookups for a
  595. :class:`~django.db.models.BooleanField`.
  596. >>> Event.objects.filter(ages__isempty=True)
  597. <QuerySet []>
  598. Defining your own range types
  599. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  600. PostgreSQL allows the definition of custom range types. Django's model and form
  601. field implementations use base classes below, and psycopg2 provides a
  602. :func:`~psycopg2:psycopg2.extras.register_range` to allow use of custom range
  603. types.
  604. .. class:: RangeField(**options)
  605. Base class for model range fields.
  606. .. attribute:: base_field
  607. The model field class to use.
  608. .. attribute:: range_type
  609. The psycopg2 range type to use.
  610. .. attribute:: form_field
  611. The form field class to use. Should be a subclass of
  612. :class:`django.contrib.postgres.forms.BaseRangeField`.
  613. .. class:: django.contrib.postgres.forms.BaseRangeField
  614. Base class for form range fields.
  615. .. attribute:: base_field
  616. The form field to use.
  617. .. attribute:: range_type
  618. The psycopg2 range type to use.