fields.txt 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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>]>
  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, the usage of this field is only supported on PostgreSQL
  340. versions at least 9.4**.
  341. Querying JSONField
  342. ^^^^^^^^^^^^^^^^^^
  343. We will use the following example model::
  344. from django.contrib.postgres.fields import JSONField
  345. from django.db import models
  346. class Dog(models.Model):
  347. name = models.CharField(max_length=200)
  348. data = JSONField()
  349. def __str__(self): # __unicode__ on Python 2
  350. return self.name
  351. .. fieldlookup:: jsonfield.key
  352. Key, index, and path lookups
  353. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  354. To query based on a given dictionary key, simply use that key as the lookup
  355. name::
  356. >>> Dog.objects.create(name='Rufus', data={
  357. ... 'breed': 'labrador',
  358. ... 'owner': {
  359. ... 'name': 'Bob',
  360. ... 'other_pets': [{
  361. ... 'name': 'Fishy',
  362. ... }],
  363. ... },
  364. ... })
  365. >>> Dog.objects.create(name='Meg', data={'breed': 'collie'})
  366. >>> Dog.objects.filter(data__breed='collie')
  367. <QuerySet [<Dog: Meg>]>
  368. Multiple keys can be chained together to form a path lookup::
  369. >>> Dog.objects.filter(data__owner__name='Bob')
  370. <QuerySet [<QuerySet <Dog: Rufus>]>
  371. If the key is an integer, it will be interpreted as an index lookup in an
  372. array::
  373. >>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy')
  374. <QuerySet [<Dog: Rufus>]>
  375. If the key you wish to query by clashes with the name of another lookup, use
  376. the :lookup:`jsonfield.contains` lookup instead.
  377. If only one key or index is used, the SQL operator ``->`` is used. If multiple
  378. operators are used then the ``#>`` operator is used.
  379. .. warning::
  380. Since any string could be a key in a JSON object, any lookup other than
  381. those listed below will be interpreted as a key lookup. No errors are
  382. raised. Be extra careful for typing mistakes, and always check your queries
  383. work as you intend.
  384. Containment and key operations
  385. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  386. .. fieldlookup:: jsonfield.contains
  387. .. fieldlookup:: jsonfield.contained_by
  388. .. fieldlookup:: jsonfield.has_key
  389. .. fieldlookup:: jsonfield.has_any_keys
  390. .. fieldlookup:: jsonfield.has_keys
  391. :class:`~django.contrib.postgres.fields.JSONField` shares lookups relating to
  392. containment and keys with :class:`~django.contrib.postgres.fields.HStoreField`.
  393. - :lookup:`contains <hstorefield.contains>` (accepts any JSON rather than
  394. just a dictionary of strings)
  395. - :lookup:`contained_by <hstorefield.contained_by>` (accepts any JSON
  396. rather than just a dictionary of strings)
  397. - :lookup:`has_key <hstorefield.has_key>`
  398. - :lookup:`has_any_keys <hstorefield.has_any_keys>`
  399. - :lookup:`has_keys <hstorefield.has_keys>`
  400. .. _range-fields:
  401. Range Fields
  402. ------------
  403. There are five range field types, corresponding to the built-in range types in
  404. PostgreSQL. These fields are used to store a range of values; for example the
  405. start and end timestamps of an event, or the range of ages an activity is
  406. suitable for.
  407. All of the range fields translate to :ref:`psycopg2 Range objects
  408. <psycopg2:adapt-range>` in python, but also accept tuples as input if no bounds
  409. information is necessary. The default is lower bound included, upper bound
  410. excluded.
  411. IntegerRangeField
  412. ^^^^^^^^^^^^^^^^^
  413. .. class:: IntegerRangeField(**options)
  414. Stores a range of integers. Based on an
  415. :class:`~django.db.models.IntegerField`. Represented by an ``int4range`` in
  416. the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in
  417. Python.
  418. BigIntegerRangeField
  419. ^^^^^^^^^^^^^^^^^^^^
  420. .. class:: BigIntegerRangeField(**options)
  421. Stores a range of large integers. Based on a
  422. :class:`~django.db.models.BigIntegerField`. Represented by an ``int8range``
  423. in the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in
  424. Python.
  425. FloatRangeField
  426. ^^^^^^^^^^^^^^^
  427. .. class:: FloatRangeField(**options)
  428. Stores a range of floating point values. Based on a
  429. :class:`~django.db.models.FloatField`. Represented by a ``numrange`` in the
  430. database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in Python.
  431. DateTimeRangeField
  432. ^^^^^^^^^^^^^^^^^^
  433. .. class:: DateTimeRangeField(**options)
  434. Stores a range of timestamps. Based on a
  435. :class:`~django.db.models.DateTimeField`. Represented by a ``tztsrange`` in
  436. the database and a :class:`~psycopg2:psycopg2.extras.DateTimeTZRange` in
  437. Python.
  438. DateRangeField
  439. ^^^^^^^^^^^^^^
  440. .. class:: DateRangeField(**options)
  441. Stores a range of dates. Based on a
  442. :class:`~django.db.models.DateField`. Represented by a ``daterange`` in the
  443. database and a :class:`~psycopg2:psycopg2.extras.DateRange` in Python.
  444. Querying Range Fields
  445. ^^^^^^^^^^^^^^^^^^^^^
  446. There are a number of custom lookups and transforms for range fields. They are
  447. available on all the above fields, but we will use the following example
  448. model::
  449. from django.contrib.postgres.fields import IntegerRangeField
  450. from django.db import models
  451. class Event(models.Model):
  452. name = models.CharField(max_length=200)
  453. ages = IntegerRangeField()
  454. start = models.DateTimeField()
  455. def __str__(self): # __unicode__ on Python 2
  456. return self.name
  457. We will also use the following example objects::
  458. >>> import datetime
  459. >>> from django.utils import timezone
  460. >>> now = timezone.now()
  461. >>> Event.objects.create(name='Soft play', ages=(0, 10), start=now)
  462. >>> Event.objects.create(name='Pub trip', ages=(21, None), start=now - datetime.timedelta(days=1))
  463. and ``NumericRange``:
  464. >>> from psycopg2.extras import NumericRange
  465. Containment functions
  466. ~~~~~~~~~~~~~~~~~~~~~
  467. As with other PostgreSQL fields, there are three standard containment
  468. operators: ``contains``, ``contained_by`` and ``overlap``, using the SQL
  469. operators ``@>``, ``<@``, and ``&&`` respectively.
  470. .. fieldlookup:: rangefield.contains
  471. contains
  472. ''''''''
  473. >>> Event.objects.filter(ages__contains=NumericRange(4, 5))
  474. <QuerySet [<Event: Soft play>]>
  475. .. fieldlookup:: rangefield.contained_by
  476. contained_by
  477. ''''''''''''
  478. >>> Event.objects.filter(ages__contained_by=NumericRange(0, 15))
  479. <QuerySet [<Event: Soft play>]>
  480. .. versionadded 1.9
  481. The `contained_by` lookup is also available on the non-range field types:
  482. :class:`~django.db.models.fields.IntegerField`,
  483. :class:`~django.db.models.fields.BigIntegerField`,
  484. :class:`~django.db.models.fields.FloatField`,
  485. :class:`~django.db.models.fields.DateField`, and
  486. :class:`~django.db.models.fields.DateTimeField`. For example::
  487. >>> from psycopg2.extras import DateTimeTZRange
  488. >>> Event.objects.filter(start__contained_by=DateTimeTZRange(
  489. ... timezone.now() - datetime.timedelta(hours=1),
  490. ... timezone.now() + datetime.timedelta(hours=1),
  491. ... )
  492. <QuerySet [<Event: Soft play>]>
  493. .. fieldlookup:: rangefield.overlap
  494. overlap
  495. '''''''
  496. >>> Event.objects.filter(ages__overlap=NumericRange(8, 12))
  497. <QuerySet [<Event: Soft play>]>
  498. Comparison functions
  499. ~~~~~~~~~~~~~~~~~~~~
  500. Range fields support the standard lookups: :lookup:`lt`, :lookup:`gt`,
  501. :lookup:`lte` and :lookup:`gte`. These are not particularly helpful - they
  502. compare the lower bounds first and then the upper bounds only if necessary.
  503. This is also the strategy used to order by a range field. It is better to use
  504. the specific range comparison operators.
  505. .. fieldlookup:: rangefield.fully_lt
  506. fully_lt
  507. ''''''''
  508. The returned ranges are strictly less than the passed range. In other words,
  509. all the points in the returned range are less than all those in the passed
  510. range.
  511. >>> Event.objects.filter(ages__fully_lt=NumericRange(11, 15))
  512. <QuerySet [<Event: Soft play>]>
  513. .. fieldlookup:: rangefield.fully_gt
  514. fully_gt
  515. ''''''''
  516. The returned ranges are strictly greater than the passed range. In other words,
  517. the all the points in the returned range are greater than all those in the
  518. passed range.
  519. >>> Event.objects.filter(ages__fully_gt=NumericRange(11, 15))
  520. <QuerySet [<Event: Pub trip>]>
  521. .. fieldlookup:: rangefield.not_lt
  522. not_lt
  523. ''''''
  524. The returned ranges do not contain any points less than the passed range, that
  525. is the lower bound of the returned range is at least the lower bound of the
  526. passed range.
  527. >>> Event.objects.filter(ages__not_lt=NumericRange(0, 15))
  528. <QuerySet [<Event: Soft play>, <Event: Pub trip>]>
  529. .. fieldlookup:: rangefield.not_gt
  530. not_gt
  531. ''''''
  532. The returned ranges do not contain any points greater than the passed range, that
  533. is the upper bound of the returned range is at most the upper bound of the
  534. passed range.
  535. >>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))
  536. <QuerySet [<Event: Soft play>]>
  537. .. fieldlookup:: rangefield.adjacent_to
  538. adjacent_to
  539. '''''''''''
  540. The returned ranges share a bound with the passed range.
  541. >>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21))
  542. <QuerySet [<Event: Soft play>, <Event: Pub trip>]>
  543. Querying using the bounds
  544. ~~~~~~~~~~~~~~~~~~~~~~~~~
  545. There are three transforms available for use in queries. You can extract the
  546. lower or upper bound, or query based on emptiness.
  547. .. fieldlookup:: rangefield.startswith
  548. startswith
  549. ''''''''''
  550. Returned objects have the given lower bound. Can be chained to valid lookups
  551. for the base field.
  552. >>> Event.objects.filter(ages__startswith=21)
  553. <QuerySet [<Event: Pub trip>]>
  554. .. fieldlookup:: rangefield.endswith
  555. endswith
  556. ''''''''
  557. Returned objects have the given upper bound. Can be chained to valid lookups
  558. for the base field.
  559. >>> Event.objects.filter(ages__endswith=10)
  560. <QuerySet [<Event: Soft play>]>
  561. .. fieldlookup:: rangefield.isempty
  562. isempty
  563. '''''''
  564. Returned objects are empty ranges. Can be chained to valid lookups for a
  565. :class:`~django.db.models.BooleanField`.
  566. >>> Event.objects.filter(ages__isempty=True)
  567. <QuerySet []>
  568. Defining your own range types
  569. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  570. PostgreSQL allows the definition of custom range types. Django's model and form
  571. field implementations use base classes below, and psycopg2 provides a
  572. :func:`~psycopg2:psycopg2.extras.register_range` to allow use of custom range
  573. types.
  574. .. class:: RangeField(**options)
  575. Base class for model range fields.
  576. .. attribute:: base_field
  577. The model field to use.
  578. .. attribute:: range_type
  579. The psycopg2 range type to use.
  580. .. attribute:: form_field
  581. The form field class to use. Should be a subclass of
  582. :class:`django.contrib.postgres.forms.BaseRangeField`.
  583. .. class:: django.contrib.postgres.forms.BaseRangeField
  584. Base class for form range fields.
  585. .. attribute:: base_field
  586. The form field to use.
  587. .. attribute:: range_type
  588. The psycopg2 range type to use.