Range Fields description

Introduction

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 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))
<QuerySet [<Event: Soft play>]>

contained_by

>>> Event.objects.filter(ages__contained_by=NumericRange(0, 15))
<QuerySet [<Event: Soft play>]>

The contained_by lookup is also available on the non-range field types: SmallAutoField , AutoField , BigAutoField , SmallIntegerField , IntegerField , BigIntegerField , DecimalField , FloatField , DateField , and 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),
... )
<QuerySet [<Event: Soft play>]>

Changed in version 3.1: Support for SmallAutoField , AutoField , BigAutoField , SmallIntegerField , and DecimalField was added.

overlap

>>> Event.objects.filter(ages__overlap=NumericRange(8, 12))
<QuerySet [<Event: Soft play>]>

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))
<QuerySet [<Event: Soft play>]>

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))
<QuerySet [<Event: Pub trip>]>

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))
<QuerySet [<Event: Soft play>, <Event: Pub trip>]>

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))
<QuerySet [<Event: Soft play>]>

adjacent_to

The returned ranges share a bound with the passed range.

>>> Event.objects.filter(ages__adjacent_to=NumericRange(10, 21))
<QuerySet [<Event: Soft play>, <Event: Pub trip>]>

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)
<QuerySet [<Event: Pub trip>]>

endswith

Returned objects have the given upper bound. Can be chained to valid lookups for the base field.

>>> Event.objects.filter(ages__endswith=10)
<QuerySet [<Event: Soft play>]>

isempty

Returned objects are empty ranges. Can be chained to valid lookups for a BooleanField .

>>> Event.objects.filter(ages__isempty=True)
<QuerySet []>

lower_inc

New in version 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 BooleanField .

>>> Event.objects.filter(ages__lower_inc=True)
<QuerySet [<Event: Soft play>, <Event: Pub trip>]>

lower_inf

New in version 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 BooleanField .

>>> Event.objects.filter(ages__lower_inf=True)
<QuerySet []>

upper_inc

New in version 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 BooleanField .

>>> Event.objects.filter(ages__upper_inc=True)
<QuerySet []>

upper_inf

New in version 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 BooleanField .

>>> Event.objects.filter(ages__upper_inf=True)
<QuerySet [<Event: Pub trip>]>

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 register_range() to allow use of custom range types.

class RangeField ( ** options )

Base class for model range fields.

base_field

The model field class to use.

range_type

The psycopg2 range type to use.

form_field

The form field class to use. Should be a subclass of django.contrib.postgres.forms.BaseRangeField .

class django.contrib.postgres.forms. BaseRangeField

Base class for form range fields.

base_field

The form field to use.

range_type

The psycopg2 range type to use.