.. _django_range_fields_desc: =================================================== **Range Fields** description =================================================== .. seealso:: - https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#range-fields - https://docs.djangoproject.com/fr/3.0/ref/contrib/postgres/fields/ - https://github.com/django/django/blob/master/docs/ref/contrib/postgres/fields.txt - :ref:`postgresql_range_types` .. contents:: :depth: 3 Introduction ============= There are **five range field types**, corresponding to the built-in :ref:`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 ` in Python, but also accept tuples as input if no bounds information is necessary. The default is lower bound included, upper bound excluded; that is, ``[)``. Querying Range Fields ======================== 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() start = models.DateTimeField() def __str__(self): return self.name We will also use the following example objects:: >>> 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)) 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. ``contains`` --------------- :: >>> Event.objects.filter(ages__contains=NumericRange(4, 5)) ]> ``contained_by`` ------------------- :: >>> Event.objects.filter(ages__contained_by=NumericRange(0, 15)) ]> The ``contained_by`` lookup is also available on the non-range field types: :class:`~django.db.models.SmallAutoField`, :class:`~django.db.models.AutoField`, :class:`~django.db.models.BigAutoField`, :class:`~django.db.models.SmallIntegerField`, :class:`~django.db.models.IntegerField`, :class:`~django.db.models.BigIntegerField`, :class:`~django.db.models.DecimalField`, :class:`~django.db.models.FloatField`, :class:`~django.db.models.DateField`, and :class:`~django.db.models.DateTimeField`. For example:: >>> from psycopg2.extras import DateTimeTZRange >>> Event.objects.filter(start__contained_by=DateTimeTZRange( ... timezone.now() - datetime.timedelta(hours=1), ... timezone.now() + datetime.timedelta(hours=1), ... ) ]> .. versionchanged:: 3.1 Support for :class:`~django.db.models.SmallAutoField`, :class:`~django.db.models.AutoField`, :class:`~django.db.models.BigAutoField`, :class:`~django.db.models.SmallIntegerField`, and :class:`~django.db.models.DecimalField` was added. ``overlap`` ------------- >>> Event.objects.filter(ages__overlap=NumericRange(8, 12)) ]> Comparison functions ====================== Range fields support the standard lookups: `lt`, `gt`, `lte` and `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. ``fully_lt`` --------------- 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)) ]> ``fully_gt`` ------------- 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)) ]> ``not_lt`` ------------ 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)) , ]> ``not_gt`` ------------ 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)) ]> ``adjacent_to`` --------------- The returned ranges share a bound with the passed range. >>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21)) , ]> .. _range_fields_querying_bounds: 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. ``startswith`` ----------------- Returned objects have the given lower bound. Can be chained to valid lookups for the base field. >>> Event.objects.filter(ages__startswith=21) ]> ``endswith`` ------------- Returned objects have the given upper bound. Can be chained to valid lookups for the base field. >>> Event.objects.filter(ages__endswith=10) ]> ``isempty`` ------------- Returned objects are empty ranges. Can be chained to valid lookups for a :class:`~django.db.models.BooleanField`. >>> Event.objects.filter(ages__isempty=True) ``lower_inc`` -------------- .. versionadded:: 3.1 Returns objects that have inclusive or exclusive lower bounds, depending on the boolean value passed. Can be chained to valid lookups for a :class:`~django.db.models.BooleanField`. >>> Event.objects.filter(ages__lower_inc=True) , ]> ``lower_inf`` -------------------- .. versionadded:: 3.1 Returns objects that have unbounded (infinite) or bounded lower bound, depending on the boolean value passed. Can be chained to valid lookups for a :class:`~django.db.models.BooleanField`. >>> Event.objects.filter(ages__lower_inf=True) ``upper_inc`` --------------- .. versionadded:: 3.1 Returns objects that have inclusive or exclusive upper bounds, depending on the boolean value passed. Can be chained to valid lookups for a :class:`~django.db.models.BooleanField`. >>> Event.objects.filter(ages__upper_inc=True) ``upper_inf`` ---------------- .. versionadded:: 3.1 Returns objects that have unbounded (infinite) or bounded upper bound, depending on the boolean value passed. Can be chained to valid lookups for a :class:`~django.db.models.BooleanField`. >>> Event.objects.filter(ages__upper_inf=True) ]> Defining your own range types ================================= **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 The model field class to use. .. attribute:: range_type The psycopg2 range type to use. .. attribute:: form_field The form field class to use. Should be a subclass of :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.