fields.txt 27 KB

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