2016-01-03 10:56:22 +00:00
|
|
|
================================
|
2014-03-26 16:44:21 +00:00
|
|
|
PostgreSQL specific model fields
|
|
|
|
================================
|
|
|
|
|
|
|
|
All of these fields are available from the ``django.contrib.postgres.fields``
|
|
|
|
module.
|
|
|
|
|
|
|
|
.. currentmodule:: django.contrib.postgres.fields
|
|
|
|
|
2017-10-09 16:19:08 +00:00
|
|
|
Indexing these fields
|
|
|
|
=====================
|
|
|
|
|
|
|
|
:class:`~django.db.models.Index` and :attr:`.Field.db_index` both create a
|
|
|
|
B-tree index, which isn't particularly helpful when querying complex data types.
|
|
|
|
Indexes such as :class:`~django.contrib.postgres.indexes.GinIndex` and
|
|
|
|
:class:`~django.contrib.postgres.indexes.GistIndex` are better suited, though
|
|
|
|
the index choice is dependent on the queries that you're using. Generally, GiST
|
|
|
|
may be a good choice for the :ref:`range fields <range-fields>` and
|
|
|
|
:class:`HStoreField`, and GIN may be helpful for :class:`ArrayField` and
|
|
|
|
:class:`JSONField`.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``ArrayField``
|
|
|
|
==============
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
.. class:: ArrayField(base_field, size=None, **options)
|
|
|
|
|
|
|
|
A field for storing lists of data. Most field types can be used, you simply
|
|
|
|
pass another field instance as the :attr:`base_field
|
|
|
|
<ArrayField.base_field>`. You may also specify a :attr:`size
|
|
|
|
<ArrayField.size>`. ``ArrayField`` can be nested to store multi-dimensional
|
|
|
|
arrays.
|
|
|
|
|
2015-07-31 16:16:45 +00:00
|
|
|
If you give the field a :attr:`~django.db.models.Field.default`, ensure
|
|
|
|
it's a callable such as ``list`` (for an empty default) or a callable that
|
|
|
|
returns a list (such as a function). Incorrectly using ``default=[]``
|
|
|
|
creates a mutable default that is shared between all instances of
|
|
|
|
``ArrayField``.
|
|
|
|
|
2014-03-26 16:44:21 +00:00
|
|
|
.. attribute:: base_field
|
|
|
|
|
|
|
|
This is a required argument.
|
|
|
|
|
2014-05-27 23:46:48 +00:00
|
|
|
Specifies the underlying data type and behavior for the array. It
|
2014-03-26 16:44:21 +00:00
|
|
|
should be an instance of a subclass of
|
|
|
|
:class:`~django.db.models.Field`. For example, it could be an
|
|
|
|
:class:`~django.db.models.IntegerField` or a
|
|
|
|
:class:`~django.db.models.CharField`. Most field types are permitted,
|
|
|
|
with the exception of those handling relational data
|
|
|
|
(:class:`~django.db.models.ForeignKey`,
|
|
|
|
:class:`~django.db.models.OneToOneField` and
|
|
|
|
:class:`~django.db.models.ManyToManyField`).
|
|
|
|
|
|
|
|
It is possible to nest array fields - you can specify an instance of
|
|
|
|
``ArrayField`` as the ``base_field``. For example::
|
|
|
|
|
|
|
|
from django.contrib.postgres.fields import ArrayField
|
2018-05-07 11:46:29 +00:00
|
|
|
from django.db import models
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
class ChessBoard(models.Model):
|
|
|
|
board = ArrayField(
|
|
|
|
ArrayField(
|
2015-02-05 09:09:13 +00:00
|
|
|
models.CharField(max_length=10, blank=True),
|
|
|
|
size=8,
|
|
|
|
),
|
|
|
|
size=8,
|
|
|
|
)
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
Transformation of values between the database and the model, validation
|
|
|
|
of data and configuration, and serialization are all delegated to the
|
|
|
|
underlying base field.
|
|
|
|
|
|
|
|
.. attribute:: size
|
|
|
|
|
|
|
|
This is an optional argument.
|
|
|
|
|
|
|
|
If passed, the array will have a maximum size as specified. This will
|
|
|
|
be passed to the database, although PostgreSQL at present does not
|
|
|
|
enforce the restriction.
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
When nesting ``ArrayField``, whether you use the `size` parameter or not,
|
|
|
|
PostgreSQL requires that the arrays are rectangular::
|
|
|
|
|
|
|
|
from django.contrib.postgres.fields import ArrayField
|
2014-03-14 17:34:49 +00:00
|
|
|
from django.db import models
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
class Board(models.Model):
|
|
|
|
pieces = ArrayField(ArrayField(models.IntegerField()))
|
|
|
|
|
|
|
|
# Valid
|
|
|
|
Board(pieces=[
|
|
|
|
[2, 3],
|
|
|
|
[2, 1],
|
|
|
|
])
|
|
|
|
|
|
|
|
# Not valid
|
|
|
|
Board(pieces=[
|
|
|
|
[2, 3],
|
|
|
|
[2],
|
|
|
|
])
|
|
|
|
|
|
|
|
If irregular shapes are required, then the underlying field should be made
|
|
|
|
nullable and the values padded with ``None``.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
Querying ``ArrayField``
|
|
|
|
-----------------------
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
There are a number of custom lookups and transforms for :class:`ArrayField`.
|
|
|
|
We will use the following example model::
|
|
|
|
|
|
|
|
from django.contrib.postgres.fields import ArrayField
|
2018-05-07 11:46:29 +00:00
|
|
|
from django.db import models
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
class Post(models.Model):
|
|
|
|
name = models.CharField(max_length=200)
|
|
|
|
tags = ArrayField(models.CharField(max_length=200), blank=True)
|
|
|
|
|
2017-01-18 16:51:29 +00:00
|
|
|
def __str__(self):
|
2014-03-26 16:44:21 +00:00
|
|
|
return self.name
|
|
|
|
|
|
|
|
.. fieldlookup:: arrayfield.contains
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``contains``
|
|
|
|
~~~~~~~~~~~~
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
The :lookup:`contains` lookup is overridden on :class:`ArrayField`. The
|
|
|
|
returned objects will be those where the values passed are a subset of the
|
|
|
|
data. It uses the SQL operator ``@>``. For example::
|
|
|
|
|
|
|
|
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
|
|
|
|
>>> Post.objects.create(name='Second post', tags=['thoughts'])
|
|
|
|
>>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
|
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__contains=['thoughts'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>, <Post: Second post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__contains=['django'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>, <Post: Third post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__contains=['django', 'thoughts'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: arrayfield.contained_by
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``contained_by``
|
|
|
|
~~~~~~~~~~~~~~~~
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
This is the inverse of the :lookup:`contains <arrayfield.contains>` lookup -
|
|
|
|
the objects returned will be those where the data is a subset of the values
|
|
|
|
passed. It uses the SQL operator ``<@``. For example::
|
|
|
|
|
|
|
|
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
|
|
|
|
>>> Post.objects.create(name='Second post', tags=['thoughts'])
|
|
|
|
>>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
|
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__contained_by=['thoughts', 'django'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>, <Post: Second post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__contained_by=['thoughts', 'django', 'tutorial'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: arrayfield.overlap
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``overlap``
|
|
|
|
~~~~~~~~~~~
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
Returns objects where the data shares any results with the values passed. Uses
|
|
|
|
the SQL operator ``&&``. For example::
|
|
|
|
|
|
|
|
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
|
|
|
|
>>> Post.objects.create(name='Second post', tags=['thoughts'])
|
|
|
|
>>> Post.objects.create(name='Third post', tags=['tutorial', 'django'])
|
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__overlap=['thoughts'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>, <Post: Second post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__overlap=['thoughts', 'tutorial'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
2014-05-22 12:42:31 +00:00
|
|
|
.. fieldlookup:: arrayfield.len
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``len``
|
|
|
|
~~~~~~~
|
2014-05-22 12:42:31 +00:00
|
|
|
|
|
|
|
Returns the length of the array. The lookups available afterwards are those
|
|
|
|
available for :class:`~django.db.models.IntegerField`. For example::
|
|
|
|
|
|
|
|
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
|
|
|
|
>>> Post.objects.create(name='Second post', tags=['thoughts'])
|
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__len=1)
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: Second post>]>
|
2014-05-22 12:42:31 +00:00
|
|
|
|
2014-03-26 16:44:21 +00:00
|
|
|
.. fieldlookup:: arrayfield.index
|
|
|
|
|
|
|
|
Index transforms
|
|
|
|
~~~~~~~~~~~~~~~~
|
|
|
|
|
2017-09-29 07:38:57 +00:00
|
|
|
Index transforms index into the array. Any non-negative integer can be used.
|
|
|
|
There are no errors if it exceeds the :attr:`size <ArrayField.size>` of the
|
|
|
|
array. The lookups available after the transform are those from the
|
|
|
|
:attr:`base_field <ArrayField.base_field>`. For example::
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
|
|
|
|
>>> Post.objects.create(name='Second post', tags=['thoughts'])
|
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__0='thoughts')
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>, <Post: Second post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__1__iexact='Django')
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__276='javascript')
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet []>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
PostgreSQL uses 1-based indexing for array fields when writing raw SQL.
|
|
|
|
However these indexes and those used in :lookup:`slices <arrayfield.slice>`
|
|
|
|
use 0-based indexing to be consistent with Python.
|
|
|
|
|
|
|
|
.. fieldlookup:: arrayfield.slice
|
|
|
|
|
|
|
|
Slice transforms
|
|
|
|
~~~~~~~~~~~~~~~~
|
|
|
|
|
2017-09-29 07:38:57 +00:00
|
|
|
Slice transforms take a slice of the array. Any two non-negative integers can
|
|
|
|
be used, separated by a single underscore. The lookups available after the
|
|
|
|
transform do not change. For example::
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
>>> Post.objects.create(name='First post', tags=['thoughts', 'django'])
|
|
|
|
>>> Post.objects.create(name='Second post', tags=['thoughts'])
|
|
|
|
>>> Post.objects.create(name='Third post', tags=['django', 'python', 'thoughts'])
|
|
|
|
|
|
|
|
>>> Post.objects.filter(tags__0_1=['thoughts'])
|
2015-12-10 13:03:38 +00:00
|
|
|
<QuerySet [<Post: First post>, <Post: Second post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
2015-12-10 13:03:38 +00:00
|
|
|
>>> Post.objects.filter(tags__0_2__contains=['thoughts'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Post: First post>, <Post: Second post>]>
|
2014-03-26 16:44:21 +00:00
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
PostgreSQL uses 1-based indexing for array fields when writing raw SQL.
|
|
|
|
However these slices and those used in :lookup:`indexes <arrayfield.index>`
|
|
|
|
use 0-based indexing to be consistent with Python.
|
|
|
|
|
|
|
|
.. admonition:: Multidimensional arrays with indexes and slices
|
|
|
|
|
2014-05-27 23:46:48 +00:00
|
|
|
PostgreSQL has some rather esoteric behavior when using indexes and slices
|
2014-03-26 16:44:21 +00:00
|
|
|
on multidimensional arrays. It will always work to use indexes to reach
|
|
|
|
down to the final underlying data, but most other slices behave strangely
|
|
|
|
at the database level and cannot be supported in a logical, consistent
|
|
|
|
fashion by Django.
|
|
|
|
|
2017-02-11 12:16:35 +00:00
|
|
|
``CIText`` fields
|
|
|
|
=================
|
2016-06-01 21:43:59 +00:00
|
|
|
|
2017-02-11 12:16:35 +00:00
|
|
|
.. class:: CIText(**options)
|
2016-06-01 21:43:59 +00:00
|
|
|
|
2017-02-11 12:16:35 +00:00
|
|
|
A mixin to create case-insensitive text fields backed by the citext_ type.
|
|
|
|
Read about `the performance considerations`_ prior to using it.
|
|
|
|
|
|
|
|
To use ``citext``, use the :class:`.CITextExtension` operation to
|
|
|
|
:ref:`setup the citext extension <create-postgresql-extensions>` in
|
|
|
|
PostgreSQL before the first ``CreateModel`` migration operation.
|
|
|
|
|
2019-01-24 18:02:37 +00:00
|
|
|
If you're using an :class:`~django.contrib.postgres.fields.ArrayField`
|
|
|
|
of ``CIText`` fields, you must add ``'django.contrib.postgres'`` in your
|
|
|
|
:setting:`INSTALLED_APPS`, otherwise field values will appear as strings
|
|
|
|
like ``'{thoughts,django}'``.
|
|
|
|
|
2017-02-11 12:16:35 +00:00
|
|
|
Several fields that use the mixin are provided:
|
|
|
|
|
|
|
|
.. class:: CICharField(**options)
|
|
|
|
.. class:: CIEmailField(**options)
|
|
|
|
.. class:: CITextField(**options)
|
|
|
|
|
|
|
|
These fields subclass :class:`~django.db.models.CharField`,
|
|
|
|
:class:`~django.db.models.EmailField`, and
|
|
|
|
:class:`~django.db.models.TextField`, respectively.
|
2016-06-01 21:43:59 +00:00
|
|
|
|
2017-02-11 12:16:35 +00:00
|
|
|
``max_length`` won't be enforced in the database since ``citext`` behaves
|
|
|
|
similar to PostgreSQL's ``text`` type.
|
2016-06-01 21:43:59 +00:00
|
|
|
|
2019-03-30 01:49:44 +00:00
|
|
|
.. _citext: https://www.postgresql.org/docs/current/citext.html
|
|
|
|
.. _the performance considerations: https://www.postgresql.org/docs/current/citext.html#AEN178177
|
2016-06-01 21:43:59 +00:00
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``HStoreField``
|
|
|
|
===============
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
.. class:: HStoreField(**options)
|
|
|
|
|
2016-12-09 00:17:02 +00:00
|
|
|
A field for storing key-value pairs. The Python data type used is a
|
|
|
|
``dict``. Keys must be strings, and values may be either strings or nulls
|
|
|
|
(``None`` in Python).
|
2014-03-14 17:34:49 +00:00
|
|
|
|
2015-04-24 12:25:33 +00:00
|
|
|
To use this field, you'll need to:
|
|
|
|
|
2018-11-15 18:54:28 +00:00
|
|
|
#. Add ``'django.contrib.postgres'`` in your :setting:`INSTALLED_APPS`.
|
|
|
|
#. :ref:`Setup the hstore extension <create-postgresql-extensions>` in
|
2016-11-05 13:18:11 +00:00
|
|
|
PostgreSQL.
|
2015-04-24 12:25:33 +00:00
|
|
|
|
|
|
|
You'll see an error like ``can't adapt type 'dict'`` if you skip the first
|
|
|
|
step, or ``type "hstore" does not exist`` if you skip the second.
|
2015-04-16 11:22:01 +00:00
|
|
|
|
2014-03-14 17:34:49 +00:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
On occasions it may be useful to require or restrict the keys which are
|
|
|
|
valid for a given field. This can be done using the
|
|
|
|
:class:`~django.contrib.postgres.validators.KeysValidator`.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
Querying ``HStoreField``
|
|
|
|
------------------------
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
In addition to the ability to query by key, there are a number of custom
|
|
|
|
lookups available for ``HStoreField``.
|
|
|
|
|
|
|
|
We will use the following example model::
|
|
|
|
|
|
|
|
from django.contrib.postgres.fields import HStoreField
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class Dog(models.Model):
|
|
|
|
name = models.CharField(max_length=200)
|
|
|
|
data = HStoreField()
|
|
|
|
|
2017-01-18 16:51:29 +00:00
|
|
|
def __str__(self):
|
2014-03-14 17:34:49 +00:00
|
|
|
return self.name
|
|
|
|
|
|
|
|
.. fieldlookup:: hstorefield.key
|
|
|
|
|
|
|
|
Key lookups
|
|
|
|
~~~~~~~~~~~
|
|
|
|
|
|
|
|
To query based on a given key, you simply use that key as the lookup name::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
|
|
|
|
>>> Dog.objects.create(name='Meg', data={'breed': 'collie'})
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__breed='collie')
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Meg>]>
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
You can chain other lookups after key lookups::
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__breed__contains='l')
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
If the key you wish to query by clashes with the name of another lookup, you
|
|
|
|
need to use the :lookup:`hstorefield.contains` lookup instead.
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
Since any string could be a key in a hstore value, any lookup other than
|
|
|
|
those listed below will be interpreted as a key lookup. No errors are
|
|
|
|
raised. Be extra careful for typing mistakes, and always check your queries
|
|
|
|
work as you intend.
|
|
|
|
|
|
|
|
.. fieldlookup:: hstorefield.contains
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``contains``
|
|
|
|
~~~~~~~~~~~~
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
The :lookup:`contains` lookup is overridden on
|
|
|
|
:class:`~django.contrib.postgres.fields.HStoreField`. The returned objects are
|
|
|
|
those where the given ``dict`` of key-value pairs are all contained in the
|
|
|
|
field. It uses the SQL operator ``@>``. For example::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
|
|
|
|
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
|
|
|
|
>>> Dog.objects.create(name='Fred', data={})
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__contains={'owner': 'Bob'})
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__contains={'breed': 'collie'})
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Meg>]>
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: hstorefield.contained_by
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``contained_by``
|
|
|
|
~~~~~~~~~~~~~~~~
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
This is the inverse of the :lookup:`contains <hstorefield.contains>` lookup -
|
|
|
|
the objects returned will be those where the key-value pairs on the object are
|
|
|
|
a subset of those in the value passed. It uses the SQL operator ``<@``. For
|
|
|
|
example::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador', 'owner': 'Bob'})
|
|
|
|
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
|
|
|
|
>>> Dog.objects.create(name='Fred', data={})
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__contained_by={'breed': 'collie', 'owner': 'Bob'})
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Meg>, <Dog: Fred>]>
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__contained_by={'breed': 'collie'})
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Fred>]>
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: hstorefield.has_key
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``has_key``
|
|
|
|
~~~~~~~~~~~
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
Returns objects where the given key is in the data. Uses the SQL operator
|
|
|
|
``?``. For example::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
|
|
|
|
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__has_key='owner')
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Meg>]>
|
2014-03-14 17:34:49 +00:00
|
|
|
|
2015-05-30 20:22:36 +00:00
|
|
|
.. fieldlookup:: hstorefield.has_any_keys
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``has_any_keys``
|
|
|
|
~~~~~~~~~~~~~~~~
|
2015-05-30 20:22:36 +00:00
|
|
|
|
|
|
|
Returns objects where any of the given keys are in the data. Uses the SQL
|
|
|
|
operator ``?|``. For example::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
|
|
|
|
>>> Dog.objects.create(name='Meg', data={'owner': 'Bob'})
|
|
|
|
>>> Dog.objects.create(name='Fred', data={})
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__has_any_keys=['owner', 'breed'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
|
2015-05-30 20:22:36 +00:00
|
|
|
|
2014-03-14 17:34:49 +00:00
|
|
|
.. fieldlookup:: hstorefield.has_keys
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``has_keys``
|
|
|
|
~~~~~~~~~~~~
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
Returns objects where all of the given keys are in the data. Uses the SQL operator
|
|
|
|
``?&``. For example::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Rufus', data={})
|
|
|
|
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__has_keys=['breed', 'owner'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Meg>]>
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: hstorefield.keys
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``keys``
|
|
|
|
~~~~~~~~
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
Returns objects where the array of keys is the given value. Note that the order
|
|
|
|
is not guaranteed to be reliable, so this transform is mainly useful for using
|
|
|
|
in conjunction with lookups on
|
|
|
|
:class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function
|
|
|
|
``akeys()``. For example::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Rufus', data={'toy': 'bone'})
|
|
|
|
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__keys__overlap=['breed', 'toy'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Rufus>, <Dog: Meg>]>
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: hstorefield.values
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``values``
|
|
|
|
~~~~~~~~~~
|
2014-03-14 17:34:49 +00:00
|
|
|
|
|
|
|
Returns objects where the array of values is the given value. Note that the
|
|
|
|
order is not guaranteed to be reliable, so this transform is mainly useful for
|
|
|
|
using in conjunction with lookups on
|
|
|
|
:class:`~django.contrib.postgres.fields.ArrayField`. Uses the SQL function
|
|
|
|
``avalues()``. For example::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Rufus', data={'breed': 'labrador'})
|
|
|
|
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': 'Bob'})
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__values__contains=['collie'])
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Meg>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``JSONField``
|
|
|
|
=============
|
2015-05-30 21:13:58 +00:00
|
|
|
|
2016-08-11 19:05:52 +00:00
|
|
|
.. class:: JSONField(encoder=None, **options)
|
2015-05-30 21:13:58 +00:00
|
|
|
|
|
|
|
A field for storing JSON encoded data. In Python the data is represented in
|
|
|
|
its Python native format: dictionaries, lists, strings, numbers, booleans
|
|
|
|
and ``None``.
|
|
|
|
|
2016-08-11 19:05:52 +00:00
|
|
|
.. attribute:: encoder
|
|
|
|
|
|
|
|
An optional JSON-encoding class to serialize data types not supported
|
|
|
|
by the standard JSON serializer (``datetime``, ``uuid``, etc.). For
|
|
|
|
example, you can use the
|
|
|
|
:class:`~django.core.serializers.json.DjangoJSONEncoder` class or any
|
|
|
|
other :py:class:`json.JSONEncoder` subclass.
|
|
|
|
|
|
|
|
When the value is retrieved from the database, it will be in the format
|
|
|
|
chosen by the custom encoder (most often a string), so you'll need to
|
|
|
|
take extra steps to convert the value back to the initial data type
|
|
|
|
(:meth:`Model.from_db() <django.db.models.Model.from_db>` and
|
|
|
|
:meth:`Field.from_db_value() <django.db.models.Field.from_db_value>`
|
|
|
|
are two possible hooks for that purpose). Your deserialization may need
|
|
|
|
to account for the fact that you can't be certain of the input type.
|
|
|
|
For example, you run the risk of returning a ``datetime`` that was
|
|
|
|
actually a string that just happened to be in the same format chosen
|
|
|
|
for ``datetime``\s.
|
2016-01-04 16:07:05 +00:00
|
|
|
|
2015-07-31 16:16:45 +00:00
|
|
|
If you give the field a :attr:`~django.db.models.Field.default`, ensure
|
|
|
|
it's a callable such as ``dict`` (for an empty default) or a callable that
|
|
|
|
returns a dict (such as a function). Incorrectly using ``default={}``
|
|
|
|
creates a mutable default that is shared between all instances of
|
|
|
|
``JSONField``.
|
|
|
|
|
2015-05-30 21:13:58 +00:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
PostgreSQL has two native JSON based data types: ``json`` and ``jsonb``.
|
|
|
|
The main difference between them is how they are stored and how they can be
|
|
|
|
queried. PostgreSQL's ``json`` field is stored as the original string
|
|
|
|
representation of the JSON and must be decoded on the fly when queried
|
|
|
|
based on keys. The ``jsonb`` field is stored based on the actual structure
|
|
|
|
of the JSON which allows indexing. The trade-off is a small additional cost
|
|
|
|
on writing to the ``jsonb`` field. ``JSONField`` uses ``jsonb``.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
Querying ``JSONField``
|
|
|
|
----------------------
|
2015-05-30 21:13:58 +00:00
|
|
|
|
|
|
|
We will use the following example model::
|
|
|
|
|
|
|
|
from django.contrib.postgres.fields import JSONField
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class Dog(models.Model):
|
|
|
|
name = models.CharField(max_length=200)
|
|
|
|
data = JSONField()
|
|
|
|
|
2017-01-18 16:51:29 +00:00
|
|
|
def __str__(self):
|
2015-05-30 21:13:58 +00:00
|
|
|
return self.name
|
|
|
|
|
|
|
|
.. fieldlookup:: jsonfield.key
|
|
|
|
|
|
|
|
Key, index, and path lookups
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
To query based on a given dictionary key, simply use that key as the lookup
|
|
|
|
name::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Rufus', data={
|
|
|
|
... 'breed': 'labrador',
|
|
|
|
... 'owner': {
|
|
|
|
... 'name': 'Bob',
|
|
|
|
... 'other_pets': [{
|
|
|
|
... 'name': 'Fishy',
|
|
|
|
... }],
|
|
|
|
... },
|
|
|
|
... })
|
2018-02-20 15:47:12 +00:00
|
|
|
>>> Dog.objects.create(name='Meg', data={'breed': 'collie', 'owner': None})
|
2015-05-30 21:13:58 +00:00
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__breed='collie')
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Meg>]>
|
2015-05-30 21:13:58 +00:00
|
|
|
|
|
|
|
Multiple keys can be chained together to form a path lookup::
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__owner__name='Bob')
|
2017-06-09 16:42:53 +00:00
|
|
|
<QuerySet [<Dog: Rufus>]>
|
2015-05-30 21:13:58 +00:00
|
|
|
|
|
|
|
If the key is an integer, it will be interpreted as an index lookup in an
|
|
|
|
array::
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__owner__other_pets__0__name='Fishy')
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Dog: Rufus>]>
|
2015-05-30 21:13:58 +00:00
|
|
|
|
|
|
|
If the key you wish to query by clashes with the name of another lookup, use
|
|
|
|
the :lookup:`jsonfield.contains` lookup instead.
|
|
|
|
|
|
|
|
If only one key or index is used, the SQL operator ``->`` is used. If multiple
|
|
|
|
operators are used then the ``#>`` operator is used.
|
|
|
|
|
2018-02-20 15:47:12 +00:00
|
|
|
To query for ``null`` in JSON data, use ``None`` as a value::
|
|
|
|
|
|
|
|
>>> Dog.objects.filter(data__owner=None)
|
|
|
|
<QuerySet [<Dog: Meg>]>
|
|
|
|
|
|
|
|
To query for missing keys, use the ``isnull`` lookup::
|
|
|
|
|
|
|
|
>>> Dog.objects.create(name='Shep', data={'breed': 'collie'})
|
|
|
|
>>> Dog.objects.filter(data__owner__isnull=True)
|
|
|
|
<QuerySet [<Dog: Shep>]>
|
|
|
|
|
2015-05-30 21:13:58 +00:00
|
|
|
.. warning::
|
|
|
|
|
|
|
|
Since any string could be a key in a JSON object, any lookup other than
|
|
|
|
those listed below will be interpreted as a key lookup. No errors are
|
|
|
|
raised. Be extra careful for typing mistakes, and always check your queries
|
|
|
|
work as you intend.
|
|
|
|
|
|
|
|
Containment and key operations
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
.. fieldlookup:: jsonfield.contains
|
|
|
|
.. fieldlookup:: jsonfield.contained_by
|
|
|
|
.. fieldlookup:: jsonfield.has_key
|
|
|
|
.. fieldlookup:: jsonfield.has_any_keys
|
|
|
|
.. fieldlookup:: jsonfield.has_keys
|
|
|
|
|
|
|
|
:class:`~django.contrib.postgres.fields.JSONField` shares lookups relating to
|
|
|
|
containment and keys with :class:`~django.contrib.postgres.fields.HStoreField`.
|
|
|
|
|
|
|
|
- :lookup:`contains <hstorefield.contains>` (accepts any JSON rather than
|
|
|
|
just a dictionary of strings)
|
|
|
|
- :lookup:`contained_by <hstorefield.contained_by>` (accepts any JSON
|
|
|
|
rather than just a dictionary of strings)
|
|
|
|
- :lookup:`has_key <hstorefield.has_key>`
|
|
|
|
- :lookup:`has_any_keys <hstorefield.has_any_keys>`
|
|
|
|
- :lookup:`has_keys <hstorefield.has_keys>`
|
|
|
|
|
2015-01-10 16:14:20 +00:00
|
|
|
.. _range-fields:
|
|
|
|
|
|
|
|
Range Fields
|
2016-01-03 10:56:22 +00:00
|
|
|
============
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
There are five range field types, corresponding to the built-in range types in
|
|
|
|
PostgreSQL. These fields are used to store a range of values; for example the
|
|
|
|
start and end timestamps of an event, or the range of ages an activity is
|
|
|
|
suitable for.
|
|
|
|
|
|
|
|
All of the range fields translate to :ref:`psycopg2 Range objects
|
2018-10-09 13:26:07 +00:00
|
|
|
<psycopg2:adapt-range>` in Python, but also accept tuples as input if no bounds
|
2015-01-10 16:14:20 +00:00
|
|
|
information is necessary. The default is lower bound included, upper bound
|
2016-03-12 17:17:21 +00:00
|
|
|
excluded; that is, ``[)``.
|
2015-01-10 16:14:20 +00:00
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``IntegerRangeField``
|
|
|
|
---------------------
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. class:: IntegerRangeField(**options)
|
|
|
|
|
|
|
|
Stores a range of integers. Based on an
|
|
|
|
:class:`~django.db.models.IntegerField`. Represented by an ``int4range`` in
|
|
|
|
the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in
|
|
|
|
Python.
|
|
|
|
|
2016-03-12 17:17:21 +00:00
|
|
|
Regardless of the bounds specified when saving the data, PostgreSQL always
|
|
|
|
returns a range in a canonical form that includes the lower bound and
|
|
|
|
excludes the upper bound; that is ``[)``.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``BigIntegerRangeField``
|
|
|
|
------------------------
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. class:: BigIntegerRangeField(**options)
|
|
|
|
|
|
|
|
Stores a range of large integers. Based on a
|
|
|
|
:class:`~django.db.models.BigIntegerField`. Represented by an ``int8range``
|
|
|
|
in the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in
|
|
|
|
Python.
|
|
|
|
|
2016-03-12 17:17:21 +00:00
|
|
|
Regardless of the bounds specified when saving the data, PostgreSQL always
|
|
|
|
returns a range in a canonical form that includes the lower bound and
|
|
|
|
excludes the upper bound; that is ``[)``.
|
|
|
|
|
2018-10-02 23:17:23 +00:00
|
|
|
``DecimalRangeField``
|
|
|
|
---------------------
|
|
|
|
|
|
|
|
.. class:: DecimalRangeField(**options)
|
|
|
|
|
|
|
|
.. versionadded:: 2.2
|
|
|
|
|
|
|
|
Stores a range of floating point values. Based on a
|
|
|
|
:class:`~django.db.models.DecimalField`. Represented by a ``numrange`` in
|
|
|
|
the database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in
|
|
|
|
Python.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``FloatRangeField``
|
|
|
|
-------------------
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. class:: FloatRangeField(**options)
|
|
|
|
|
|
|
|
Stores a range of floating point values. Based on a
|
|
|
|
:class:`~django.db.models.FloatField`. Represented by a ``numrange`` in the
|
|
|
|
database and a :class:`~psycopg2:psycopg2.extras.NumericRange` in Python.
|
|
|
|
|
2018-10-02 23:17:23 +00:00
|
|
|
.. deprecated:: 2.2
|
|
|
|
|
|
|
|
Use :class:`DecimalRangeField` instead.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``DateTimeRangeField``
|
|
|
|
----------------------
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. class:: DateTimeRangeField(**options)
|
|
|
|
|
|
|
|
Stores a range of timestamps. Based on a
|
2017-08-26 08:20:01 +00:00
|
|
|
:class:`~django.db.models.DateTimeField`. Represented by a ``tstzrange`` in
|
2015-01-10 16:14:20 +00:00
|
|
|
the database and a :class:`~psycopg2:psycopg2.extras.DateTimeTZRange` in
|
|
|
|
Python.
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``DateRangeField``
|
|
|
|
------------------
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. class:: DateRangeField(**options)
|
|
|
|
|
|
|
|
Stores a range of dates. Based on a
|
|
|
|
:class:`~django.db.models.DateField`. Represented by a ``daterange`` in the
|
|
|
|
database and a :class:`~psycopg2:psycopg2.extras.DateRange` in Python.
|
|
|
|
|
2016-03-12 17:17:21 +00:00
|
|
|
Regardless of the bounds specified when saving the data, PostgreSQL always
|
|
|
|
returns a range in a canonical form that includes the lower bound and
|
|
|
|
excludes the upper bound; that is ``[)``.
|
|
|
|
|
2015-01-10 16:14:20 +00:00
|
|
|
Querying Range Fields
|
2016-01-03 10:56:22 +00:00
|
|
|
---------------------
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
There are a number of custom lookups and transforms for range fields. They are
|
|
|
|
available on all the above fields, but we will use the following example
|
|
|
|
model::
|
|
|
|
|
|
|
|
from django.contrib.postgres.fields import IntegerRangeField
|
|
|
|
from django.db import models
|
|
|
|
|
|
|
|
class Event(models.Model):
|
|
|
|
name = models.CharField(max_length=200)
|
|
|
|
ages = IntegerRangeField()
|
2015-05-21 11:25:50 +00:00
|
|
|
start = models.DateTimeField()
|
2015-01-10 16:14:20 +00:00
|
|
|
|
2017-01-18 16:51:29 +00:00
|
|
|
def __str__(self):
|
2015-01-10 16:14:20 +00:00
|
|
|
return self.name
|
|
|
|
|
|
|
|
We will also use the following example objects::
|
|
|
|
|
2015-05-21 11:25:50 +00:00
|
|
|
>>> import datetime
|
|
|
|
>>> from django.utils import timezone
|
|
|
|
>>> now = timezone.now()
|
|
|
|
>>> Event.objects.create(name='Soft play', ages=(0, 10), start=now)
|
|
|
|
>>> Event.objects.create(name='Pub trip', ages=(21, None), start=now - datetime.timedelta(days=1))
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
and ``NumericRange``:
|
|
|
|
|
|
|
|
>>> from psycopg2.extras import NumericRange
|
|
|
|
|
|
|
|
Containment functions
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
As with other PostgreSQL fields, there are three standard containment
|
|
|
|
operators: ``contains``, ``contained_by`` and ``overlap``, using the SQL
|
|
|
|
operators ``@>``, ``<@``, and ``&&`` respectively.
|
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.contains
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``contains``
|
|
|
|
^^^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__contains=NumericRange(4, 5))
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Soft play>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.contained_by
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``contained_by``
|
|
|
|
^^^^^^^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__contained_by=NumericRange(0, 15))
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Soft play>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
2017-01-02 15:38:54 +00:00
|
|
|
The ``contained_by`` lookup is also available on the non-range field types:
|
|
|
|
:class:`~django.db.models.IntegerField`,
|
|
|
|
:class:`~django.db.models.BigIntegerField`,
|
|
|
|
:class:`~django.db.models.FloatField`, :class:`~django.db.models.DateField`,
|
|
|
|
and :class:`~django.db.models.DateTimeField`. For example::
|
2015-05-21 11:25:50 +00:00
|
|
|
|
|
|
|
>>> from psycopg2.extras import DateTimeTZRange
|
|
|
|
>>> Event.objects.filter(start__contained_by=DateTimeTZRange(
|
|
|
|
... timezone.now() - datetime.timedelta(hours=1),
|
|
|
|
... timezone.now() + datetime.timedelta(hours=1),
|
|
|
|
... )
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Soft play>]>
|
2015-05-21 11:25:50 +00:00
|
|
|
|
2015-01-10 16:14:20 +00:00
|
|
|
.. fieldlookup:: rangefield.overlap
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``overlap``
|
|
|
|
^^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__overlap=NumericRange(8, 12))
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Soft play>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
Comparison functions
|
|
|
|
~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
Range fields support the standard lookups: :lookup:`lt`, :lookup:`gt`,
|
|
|
|
:lookup:`lte` and :lookup:`gte`. These are not particularly helpful - they
|
|
|
|
compare the lower bounds first and then the upper bounds only if necessary.
|
|
|
|
This is also the strategy used to order by a range field. It is better to use
|
|
|
|
the specific range comparison operators.
|
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.fully_lt
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``fully_lt``
|
|
|
|
^^^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
The returned ranges are strictly less than the passed range. In other words,
|
|
|
|
all the points in the returned range are less than all those in the passed
|
|
|
|
range.
|
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__fully_lt=NumericRange(11, 15))
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Soft play>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.fully_gt
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``fully_gt``
|
|
|
|
^^^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
The returned ranges are strictly greater than the passed range. In other words,
|
|
|
|
the all the points in the returned range are greater than all those in the
|
|
|
|
passed range.
|
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__fully_gt=NumericRange(11, 15))
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Pub trip>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.not_lt
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``not_lt``
|
|
|
|
^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
The returned ranges do not contain any points less than the passed range, that
|
|
|
|
is the lower bound of the returned range is at least the lower bound of the
|
|
|
|
passed range.
|
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__not_lt=NumericRange(0, 15))
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Soft play>, <Event: Pub trip>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.not_gt
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``not_gt``
|
|
|
|
^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
The returned ranges do not contain any points greater than the passed range, that
|
|
|
|
is the upper bound of the returned range is at most the upper bound of the
|
|
|
|
passed range.
|
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Soft play>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.adjacent_to
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``adjacent_to``
|
|
|
|
^^^^^^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
The returned ranges share a bound with the passed range.
|
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21))
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Soft play>, <Event: Pub trip>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
Querying using the bounds
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
There are three transforms available for use in queries. You can extract the
|
|
|
|
lower or upper bound, or query based on emptiness.
|
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.startswith
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``startswith``
|
|
|
|
^^^^^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
Returned objects have the given lower bound. Can be chained to valid lookups
|
|
|
|
for the base field.
|
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__startswith=21)
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Pub trip>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.endswith
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``endswith``
|
|
|
|
^^^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
Returned objects have the given upper bound. Can be chained to valid lookups
|
|
|
|
for the base field.
|
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__endswith=10)
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet [<Event: Soft play>]>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. fieldlookup:: rangefield.isempty
|
|
|
|
|
2016-01-24 21:26:11 +00:00
|
|
|
``isempty``
|
|
|
|
^^^^^^^^^^^
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
Returned objects are empty ranges. Can be chained to valid lookups for a
|
|
|
|
:class:`~django.db.models.BooleanField`.
|
|
|
|
|
|
|
|
>>> Event.objects.filter(ages__isempty=True)
|
2015-10-05 23:07:34 +00:00
|
|
|
<QuerySet []>
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
Defining your own range types
|
2019-07-16 13:08:14 +00:00
|
|
|
-----------------------------
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
PostgreSQL allows the definition of custom range types. Django's model and form
|
|
|
|
field implementations use base classes below, and psycopg2 provides a
|
|
|
|
:func:`~psycopg2:psycopg2.extras.register_range` to allow use of custom range
|
|
|
|
types.
|
|
|
|
|
|
|
|
.. class:: RangeField(**options)
|
|
|
|
|
|
|
|
Base class for model range fields.
|
|
|
|
|
|
|
|
.. attribute:: base_field
|
|
|
|
|
2016-04-03 10:39:18 +00:00
|
|
|
The model field class to use.
|
2015-01-10 16:14:20 +00:00
|
|
|
|
|
|
|
.. attribute:: range_type
|
|
|
|
|
|
|
|
The psycopg2 range type to use.
|
|
|
|
|
|
|
|
.. attribute:: form_field
|
|
|
|
|
2015-01-11 18:24:13 +00:00
|
|
|
The form field class to use. Should be a subclass of
|
2015-01-10 16:14:20 +00:00
|
|
|
:class:`django.contrib.postgres.forms.BaseRangeField`.
|
|
|
|
|
|
|
|
.. class:: django.contrib.postgres.forms.BaseRangeField
|
|
|
|
|
|
|
|
Base class for form range fields.
|
|
|
|
|
|
|
|
.. attribute:: base_field
|
|
|
|
|
|
|
|
The form field to use.
|
|
|
|
|
|
|
|
.. attribute:: range_type
|
|
|
|
|
|
|
|
The psycopg2 range type to use.
|
2019-07-12 11:08:00 +00:00
|
|
|
|
|
|
|
Range operators
|
|
|
|
---------------
|
|
|
|
|
|
|
|
.. versionadded:: 3.0
|
|
|
|
|
|
|
|
.. class:: RangeOperators
|
|
|
|
|
|
|
|
PostgreSQL provides a set of SQL operators that can be used together with the
|
|
|
|
range data types (see `the PostgreSQL documentation for the full details of
|
|
|
|
range operators <https://www.postgresql.org/docs/current/
|
|
|
|
functions-range.html#RANGE-OPERATORS-TABLE>`_). This class is meant as a
|
|
|
|
convenient method to avoid typos. The operator names overlap with the names of
|
|
|
|
corresponding lookups.
|
|
|
|
|
|
|
|
.. code-block:: python
|
|
|
|
|
|
|
|
class RangeOperators:
|
|
|
|
EQUAL = '='
|
|
|
|
NOT_EQUAL = '<>'
|
|
|
|
CONTAINS = '@>'
|
|
|
|
CONTAINED_BY = '<@'
|
|
|
|
OVERLAPS = '&&'
|
|
|
|
FULLY_LT = '<<'
|
|
|
|
FULLY_GT = '>>'
|
|
|
|
NOT_LT = '&>'
|
|
|
|
NOT_GT = '&<'
|
|
|
|
ADJACENT_TO = '-|-'
|
2019-07-12 11:08:00 +00:00
|
|
|
|
|
|
|
RangeBoundary() expressions
|
|
|
|
---------------------------
|
|
|
|
|
|
|
|
.. versionadded:: 3.0
|
|
|
|
|
|
|
|
.. class:: RangeBoundary(inclusive_lower=True, inclusive_upper=False)
|
|
|
|
|
|
|
|
.. attribute:: inclusive_lower
|
|
|
|
|
|
|
|
If ``True`` (default), the lower bound is inclusive ``'['``, otherwise
|
|
|
|
it's exclusive ``'('``.
|
|
|
|
|
|
|
|
.. attribute:: inclusive_upper
|
|
|
|
|
|
|
|
If ``False`` (default), the upper bound is exclusive ``')'``, otherwise
|
|
|
|
it's inclusive ``']'``.
|
|
|
|
|
|
|
|
A ``RangeBoundary()`` expression represents the range boundaries. It can be
|
|
|
|
used with a custom range functions that expected boundaries, for example to
|
|
|
|
define :class:`~django.contrib.postgres.constraints.ExclusionConstraint`. See
|
|
|
|
`the PostgreSQL documentation for the full details <https://www.postgresql.org/
|
|
|
|
docs/current/rangetypes.html#RANGETYPES-INCLUSIVITY>`_.
|