fields.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. PostgreSQL specific model fields
  2. ================================
  3. All of these fields are available from the ``django.contrib.postgres.fields``
  4. module.
  5. .. currentmodule:: django.contrib.postgres.fields
  6. ArrayField
  7. ----------
  8. .. class:: ArrayField(base_field, size=None, **options)
  9. A field for storing lists of data. Most field types can be used, you simply
  10. pass another field instance as the :attr:`base_field
  11. <ArrayField.base_field>`. You may also specify a :attr:`size
  12. <ArrayField.size>`. ``ArrayField`` can be nested to store multi-dimensional
  13. arrays.
  14. .. attribute:: base_field
  15. This is a required argument.
  16. Specifies the underlying data type and behavior for the array. It
  17. should be an instance of a subclass of
  18. :class:`~django.db.models.Field`. For example, it could be an
  19. :class:`~django.db.models.IntegerField` or a
  20. :class:`~django.db.models.CharField`. Most field types are permitted,
  21. with the exception of those handling relational data
  22. (:class:`~django.db.models.ForeignKey`,
  23. :class:`~django.db.models.OneToOneField` and
  24. :class:`~django.db.models.ManyToManyField`).
  25. It is possible to nest array fields - you can specify an instance of
  26. ``ArrayField`` as the ``base_field``. For example::
  27. from django.db import models
  28. from django.contrib.postgres.fields import ArrayField
  29. class ChessBoard(models.Model):
  30. board = ArrayField(
  31. ArrayField(
  32. CharField(max_length=10, blank=True, null=True),
  33. size=8),
  34. size=8)
  35. Transformation of values between the database and the model, validation
  36. of data and configuration, and serialization are all delegated to the
  37. underlying base field.
  38. .. attribute:: size
  39. This is an optional argument.
  40. If passed, the array will have a maximum size as specified. This will
  41. be passed to the database, although PostgreSQL at present does not
  42. enforce the restriction.
  43. .. note::
  44. When nesting ``ArrayField``, whether you use the `size` parameter or not,
  45. PostgreSQL requires that the arrays are rectangular::
  46. from django.contrib.postgres.fields import ArrayField
  47. from django.db import models
  48. class Board(models.Model):
  49. pieces = ArrayField(ArrayField(models.IntegerField()))
  50. # Valid
  51. Board(pieces=[
  52. [2, 3],
  53. [2, 1],
  54. ])
  55. # Not valid
  56. Board(pieces=[
  57. [2, 3],
  58. [2],
  59. ])
  60. If irregular shapes are required, then the underlying field should be made
  61. nullable and the values padded with ``None``.
  62. Querying ArrayField
  63. ^^^^^^^^^^^^^^^^^^^
  64. There are a number of custom lookups and transforms for :class:`ArrayField`.
  65. We will use the following example model::
  66. from django.db import models
  67. from django.contrib.postgres.fields import ArrayField
  68. class Post(models.Model):
  69. name = models.CharField(max_length=200)
  70. tags = ArrayField(models.CharField(max_length=200), blank=True)
  71. def __str__(self): # __unicode__ on Python 2
  72. return self.name
  73. .. fieldlookup:: arrayfield.contains
  74. contains
  75. ~~~~~~~~
  76. The :lookup:`contains` lookup is overridden on :class:`ArrayField`. The
  77. returned objects will be those where the values passed are a subset of the
  78. data. It uses the SQL operator ``@>``. For example::
  79. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  80. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  81. >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
  82. >>> Post.objects.filter(tags__contains=['thoughts'])
  83. [<Post: First post>, <Post: Second post>]
  84. >>> Post.objects.filter(tags__contains=['django'])
  85. [<Post: First post>, <Post: Third post>]
  86. >>> Post.objects.filter(tags__contains=['django', 'thoughts'])
  87. [<Post: First post>]
  88. .. fieldlookup:: arrayfield.contained_by
  89. contained_by
  90. ~~~~~~~~~~~~
  91. This is the inverse of the :lookup:`contains <arrayfield.contains>` lookup -
  92. the objects returned will be those where the data is a subset of the values
  93. passed. It uses the SQL operator ``<@``. For example::
  94. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  95. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  96. >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
  97. >>> Post.objects.filter(tags__contained_by=['thoughts', 'django'])
  98. [<Post: First post>, <Post: Second post>]
  99. >>> Post.objects.filter(tags__contained_by=['thoughts', 'django', 'tutorial'])
  100. [<Post: First post>, <Post: Second post>, <Post: Third post>]
  101. .. fieldlookup:: arrayfield.overlap
  102. overlap
  103. ~~~~~~~
  104. Returns objects where the data shares any results with the values passed. Uses
  105. the SQL operator ``&&``. For example::
  106. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  107. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  108. >>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
  109. >>> Post.objects.filter(tags__overlap=['thoughts'])
  110. [<Post: First post>, <Post: Second post>]
  111. >>> Post.objects.filter(tags__overlap=['thoughts', 'tutorial'])
  112. [<Post: First post>, <Post: Second post>, <Post: Third post>]
  113. .. fieldlookup:: arrayfield.len
  114. len
  115. ~~~
  116. Returns the length of the array. The lookups available afterwards are those
  117. available for :class:`~django.db.models.IntegerField`. For example::
  118. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  119. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  120. >>> Post.objects.filter(tags__len=1)
  121. [<Post: Second post>]
  122. .. fieldlookup:: arrayfield.index
  123. Index transforms
  124. ~~~~~~~~~~~~~~~~
  125. This class of transforms allows you to index into the array in queries. Any
  126. non-negative integer can be used. There are no errors if it exceeds the
  127. :attr:`size <ArrayField.size>` of the array. The lookups available after the
  128. transform are those from the :attr:`base_field <ArrayField.base_field>`. For
  129. example::
  130. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  131. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  132. >>> Post.objects.filter(tags__0='thoughts')
  133. [<Post: First post>, <Post: Second post>]
  134. >>> Post.objects.filter(tags__1__iexact='Django')
  135. [<Post: First post>]
  136. >>> Post.objects.filter(tags__276='javascript')
  137. []
  138. .. note::
  139. PostgreSQL uses 1-based indexing for array fields when writing raw SQL.
  140. However these indexes and those used in :lookup:`slices <arrayfield.slice>`
  141. use 0-based indexing to be consistent with Python.
  142. .. fieldlookup:: arrayfield.slice
  143. Slice transforms
  144. ~~~~~~~~~~~~~~~~
  145. This class of transforms allow you to take a slice of the array. Any two
  146. non-negative integers can be used, separated by a single underscore. The
  147. lookups available after the transform do not change. For example::
  148. >>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
  149. >>> Post.objects.create(name='Second post', tags=['thoughts'])
  150. >>> Post.objects.create(name='Third post', tags=['django', 'python', 'thoughts'])
  151. >>> Post.objects.filter(tags__0_1=['thoughts'])
  152. [<Post: First post>]
  153. >>> Post.objects.filter(tags__0_2__contains='thoughts')
  154. [<Post: First post>, <Post: Second post>]
  155. .. note::
  156. PostgreSQL uses 1-based indexing for array fields when writing raw SQL.
  157. However these slices and those used in :lookup:`indexes <arrayfield.index>`
  158. use 0-based indexing to be consistent with Python.
  159. .. admonition:: Multidimensional arrays with indexes and slices
  160. PostgreSQL has some rather esoteric behavior when using indexes and slices
  161. on multidimensional arrays. It will always work to use indexes to reach
  162. down to the final underlying data, but most other slices behave strangely
  163. at the database level and cannot be supported in a logical, consistent
  164. fashion by Django.
  165. Indexing ArrayField
  166. ^^^^^^^^^^^^^^^^^^^
  167. At present using :attr:`~django.db.models.Field.db_index` will create a
  168. ``btree`` index. This does not offer particularly significant help to querying.
  169. A more useful index is a ``GIN`` index, which you should create using a
  170. :class:`~django.db.migrations.operations.RunSQL` operation.
  171. HStoreField
  172. -----------
  173. .. class:: HStoreField(**options)
  174. A field for storing mappings of strings to strings. The Python data type
  175. used is a ``dict``.
  176. .. note::
  177. On occasions it may be useful to require or restrict the keys which are
  178. valid for a given field. This can be done using the
  179. :class:`~django.contrib.postgres.validators.KeysValidator`.
  180. Querying HStoreField
  181. ^^^^^^^^^^^^^^^^^^^^
  182. In addition to the ability to query by key, there are a number of custom
  183. lookups available for ``HStoreField``.
  184. We will use the following example model::
  185. from django.contrib.postgres.fields import HStoreField
  186. from django.db import models
  187. class Dog(models.Model):
  188. name = models.CharField(max_length=200)
  189. data = HStoreField()
  190. def __str__(self): # __unicode__ on Python 2
  191. return self.name
  192. .. fieldlookup:: hstorefield.key
  193. Key lookups
  194. ~~~~~~~~~~~
  195. To query based on a given key, you simply use that key as the lookup name::
  196. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  197. >>> Dog.objects.create(name='Meg', data={'breed': 'collie'})
  198. >>> Dog.objects.filter(data__breed='collie')
  199. [<Dog: Meg>]
  200. You can chain other lookups after key lookups::
  201. >>> Dog.objects.filter(data__breed__contains='l')
  202. [<Dog: Rufus>, <Dog: Meg>]
  203. If the key you wish to query by clashes with the name of another lookup, you
  204. need to use the :lookup:`hstorefield.contains` lookup instead.
  205. .. warning::
  206. Since any string could be a key in a hstore value, any lookup other than
  207. those listed below will be interpreted as a key lookup. No errors are
  208. raised. Be extra careful for typing mistakes, and always check your queries
  209. work as you intend.
  210. .. fieldlookup:: hstorefield.contains
  211. contains
  212. ~~~~~~~~
  213. The :lookup:`contains` lookup is overridden on
  214. :class:`~django.contrib.postgres.fields.HStoreField`. The returned objects are
  215. those where the given ``dict`` of key-value pairs are all contained in the
  216. field. It uses the SQL operator ``@>``. For example::
  217. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
  218. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  219. >>> Dog.objects.create(name='Fred', data={})
  220. >>> Dog.objects.filter(data__contains={'owner': 'Bob'})
  221. [<Dog: Rufus>, <Dog: Meg>]
  222. >>> Dog.objects.filter(data__contains={'breed': 'collie'})
  223. [<Dog: Meg>]
  224. .. fieldlookup:: hstorefield.contained_by
  225. contained_by
  226. ~~~~~~~~~~~~
  227. This is the inverse of the :lookup:`contains <hstorefield.contains>` lookup -
  228. the objects returned will be those where the key-value pairs on the object are
  229. a subset of those in the value passed. It uses the SQL operator ``<@``. For
  230. example::
  231. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
  232. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  233. >>> Dog.objects.create(name='Fred', data={})
  234. >>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'})
  235. [<Dog: Meg>, <Dog: Fred>]
  236. >>> Dog.objects.filter(data__contained_by={'breed': 'collie'})
  237. [<Dog: Fred>]
  238. .. fieldlookup:: hstorefield.has_key
  239. has_key
  240. ~~~~~~~
  241. Returns objects where the given key is in the data. Uses the SQL operator
  242. ``?``. For example::
  243. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  244. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  245. >>> Dog.objects.filter(data__has_key='owner')
  246. [<Dog: Meg>]
  247. .. fieldlookup:: hstorefield.has_keys
  248. has_keys
  249. ~~~~~~~~
  250. Returns objects where all of the given keys are in the data. Uses the SQL operator
  251. ``?&``. For example::
  252. >>> Dog.objects.create(name='Rufus', data={})
  253. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  254. >>> Dog.objects.filter(data__has_keys=['breed', 'owner'])
  255. [<Dog: Meg>]
  256. .. fieldlookup:: hstorefield.keys
  257. keys
  258. ~~~~
  259. Returns objects where the array of keys is the given value. Note that the order
  260. is not guaranteed to be reliable, so this transform is mainly useful for using
  261. in conjunction with lookups on
  262. :class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function
  263. ``akeys()``. For example::
  264. >>> Dog.objects.create(name='Rufus', data={'toy': 'bone'})
  265. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  266. >>> Dog.objects.filter(data__keys__overlap=['breed', 'toy'])
  267. [<Dog: Rufus>, <Dog: Meg>]
  268. .. fieldlookup:: hstorefield.values
  269. values
  270. ~~~~~~
  271. Returns objects where the array of values is the given value. Note that the
  272. order is not guaranteed to be reliable, so this transform is mainly useful for
  273. using in conjunction with lookups on
  274. :class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function
  275. ``avalues()``. For example::
  276. >>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
  277. >>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
  278. >>> Dog.objects.filter(data__values__contains=['collie'])
  279. [<Dog: Meg>]
  280. .. _range-fields:
  281. Range Fields
  282. ------------
  283. There are five range field types, corresponding to the built-in range types in
  284. PostgreSQL. These fields are used to store a range of values; for example the
  285. start and end timestamps of an event, or the range of ages an activity is
  286. suitable for.
  287. All of the range fields translate to :ref:`psycopg2 Range objects
  288. <psycopg2:adapt-range>` in python, but also accept tuples as input if no bounds
  289. information is necessary. The default is lower bound included, upper bound
  290. excluded.
  291. IntegerRangeField
  292. ^^^^^^^^^^^^^^^^^
  293. .. class:: IntegerRangeField(**options)
  294. Stores a range of integers. Based on an
  295. :class:`~django.db.models.IntegerField`. Represented by an ``int4range`` in
  296. the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in
  297. Python.
  298. BigIntegerRangeField
  299. ^^^^^^^^^^^^^^^^^^^^
  300. .. class:: BigIntegerRangeField(**options)
  301. Stores a range of large integers. Based on a
  302. :class:`~django.db.models.BigIntegerField`. Represented by an ``int8range``
  303. in the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in
  304. Python.
  305. FloatRangeField
  306. ^^^^^^^^^^^^^^^
  307. .. class:: FloatRangeField(**options)
  308. Stores a range of floating point values. Based on a
  309. :class:`~django.db.models.FloatField`. Represented by a ``numrange`` in the
  310. database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in Python.
  311. DateTimeRangeField
  312. ^^^^^^^^^^^^^^^^^^
  313. .. class:: DateTimeRangeField(**options)
  314. Stores a range of timestamps. Based on a
  315. :class:`~django.db.models.DateTimeField`. Represented by a ``tztsrange`` in
  316. the database and a :class:`~psycopg2:psycopg2.extras.DateTimeTZRange` in
  317. Python.
  318. DateRangeField
  319. ^^^^^^^^^^^^^^
  320. .. class:: DateRangeField(**options)
  321. Stores a range of dates. Based on a
  322. :class:`~django.db.models.DateField`. Represented by a ``daterange`` in the
  323. database and a :class:`~psycopg2:psycopg2.extras.DateRange` in Python.
  324. Querying Range Fields
  325. ^^^^^^^^^^^^^^^^^^^^^
  326. There are a number of custom lookups and transforms for range fields. They are
  327. available on all the above fields, but we will use the following example
  328. model::
  329. from django.contrib.postgres.fields import IntegerRangeField
  330. from django.db import models
  331. class Event(models.Model):
  332. name = models.CharField(max_length=200)
  333. ages = IntegerRangeField()
  334. def __str__(self): # __unicode__ on Python 2
  335. return self.name
  336. We will also use the following example objects::
  337. >>> Event.objects.create(name='Soft play', ages=(0, 10))
  338. >>> Event.objects.create(name='Pub trip', ages=(21, None))
  339. and ``NumericRange``:
  340. >>> from psycopg2.extras import NumericRange
  341. Containment functions
  342. ~~~~~~~~~~~~~~~~~~~~~
  343. As with other PostgreSQL fields, there are three standard containment
  344. operators: ``contains``, ``contained_by`` and ``overlap``, using the SQL
  345. operators ``@>``, ``<@``, and ``&&`` respectively.
  346. .. fieldlookup:: rangefield.contains
  347. contains
  348. ''''''''
  349. >>> Event.objects.filter(ages__contains=NumericRange(4, 5))
  350. [<Event: Soft play>]
  351. .. fieldlookup:: rangefield.contained_by
  352. contained_by
  353. ''''''''''''
  354. >>> Event.objects.filter(ages__contained_by=NumericRange(0, 15))
  355. [<Event: Soft play>]
  356. .. fieldlookup:: rangefield.overlap
  357. overlap
  358. '''''''
  359. >>> Event.objects.filter(ages__overlap=NumericRange(8, 12))
  360. [<Event: Soft play>]
  361. Comparison functions
  362. ~~~~~~~~~~~~~~~~~~~~
  363. Range fields support the standard lookups: :lookup:`lt`, :lookup:`gt`,
  364. :lookup:`lte` and :lookup:`gte`. These are not particularly helpful - they
  365. compare the lower bounds first and then the upper bounds only if necessary.
  366. This is also the strategy used to order by a range field. It is better to use
  367. the specific range comparison operators.
  368. .. fieldlookup:: rangefield.fully_lt
  369. fully_lt
  370. ''''''''
  371. The returned ranges are strictly less than the passed range. In other words,
  372. all the points in the returned range are less than all those in the passed
  373. range.
  374. >>> Event.objects.filter(ages__fully_lt=NumericRange(11, 15))
  375. [<Event: Soft play>]
  376. .. fieldlookup:: rangefield.fully_gt
  377. fully_gt
  378. ''''''''
  379. The returned ranges are strictly greater than the passed range. In other words,
  380. the all the points in the returned range are greater than all those in the
  381. passed range.
  382. >>> Event.objects.filter(ages__fully_gt=NumericRange(11, 15))
  383. [<Event: Pub trip>]
  384. .. fieldlookup:: rangefield.not_lt
  385. not_lt
  386. ''''''
  387. The returned ranges do not contain any points less than the passed range, that
  388. is the lower bound of the returned range is at least the lower bound of the
  389. passed range.
  390. >>> Event.objects.filter(ages__not_lt=NumericRange(0, 15))
  391. [<Event: Soft play>, <Event: Pub trip>]
  392. .. fieldlookup:: rangefield.not_gt
  393. not_gt
  394. ''''''
  395. The returned ranges do not contain any points greater than the passed range, that
  396. is the upper bound of the returned range is at most the upper bound of the
  397. passed range.
  398. >>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))
  399. [<Event: Soft play>]
  400. .. fieldlookup:: rangefield.adjacent_to
  401. adjacent_to
  402. '''''''''''
  403. The returned ranges share a bound with the passed range.
  404. >>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21))
  405. [<Event: Soft play>, <Event: Pub trip>]
  406. Querying using the bounds
  407. ~~~~~~~~~~~~~~~~~~~~~~~~~
  408. There are three transforms available for use in queries. You can extract the
  409. lower or upper bound, or query based on emptiness.
  410. .. fieldlookup:: rangefield.startswith
  411. startswith
  412. ''''''''''
  413. Returned objects have the given lower bound. Can be chained to valid lookups
  414. for the base field.
  415. >>> Event.objects.filter(ages__startswith=21)
  416. [<Event: Pub trip>]
  417. .. fieldlookup:: rangefield.endswith
  418. endswith
  419. ''''''''
  420. Returned objects have the given upper bound. Can be chained to valid lookups
  421. for the base field.
  422. >>> Event.objects.filter(ages__endswith=10)
  423. [<Event: Soft play>]
  424. .. fieldlookup:: rangefield.isempty
  425. isempty
  426. '''''''
  427. Returned objects are empty ranges. Can be chained to valid lookups for a
  428. :class:`~django.db.models.BooleanField`.
  429. >>> Event.objects.filter(ages__isempty=True)
  430. []
  431. Defining your own range types
  432. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  433. PostgreSQL allows the definition of custom range types. Django's model and form
  434. field implementations use base classes below, and psycopg2 provides a
  435. :func:`~psycopg2:psycopg2.extras.register_range` to allow use of custom range
  436. types.
  437. .. class:: RangeField(**options)
  438. Base class for model range fields.
  439. .. attribute:: base_field
  440. The model field to use.
  441. .. attribute:: range_type
  442. The psycopg2 range type to use.
  443. .. attribute:: form_field
  444. The form field class to use. Should be a sublcass of
  445. :class:`django.contrib.postgres.forms.BaseRangeField`.
  446. .. class:: django.contrib.postgres.forms.BaseRangeField
  447. Base class for form range fields.
  448. .. attribute:: base_field
  449. The form field to use.
  450. .. attribute:: range_type
  451. The psycopg2 range type to use.