PostgreSQL specific model fields

All of these fields are available from the django.contrib.postgres.fields module.

Indexing these fields

Index and Field.db_index both create a B-tree index, which isn’t particularly helpful when querying complex data types. Indexes such as GinIndex and 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 range fields and HStoreField, and GIN may be helpful for ArrayField.

ArrayField

class ArrayField(base_field, size=None, **options)

A field for storing lists of data. Most field types can be used, and you pass another field instance as the base_field. You may also specify a size. ArrayField can be nested to store multi-dimensional arrays.

If you give the field a 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.

  • base_field

    This is a required argument.

    Specifies the underlying data type and behavior for the array. It should be an instance of a subclass of Field. For example, it could be an IntegerField or a CharField. Most field types are permitted, with the exception of those handling relational data (ForeignKey, OneToOneField and ManyToManyField) and file fields ( FileField and ImageField).

    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 from django.db import models

  1. class ChessBoard(models.Model):
  2. board = ArrayField(
  3. ArrayField(
  4. models.CharField(max_length=10, blank=True),
  5. size=8,
  6. ),
  7. size=8,
  8. )
  9. ```
  10. Transformation of values between the database and the model, validation of data and configuration, and serialization are all delegated to the underlying base field.
  • 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:

  1. from django.contrib.postgres.fields import ArrayField
  2. from django.db import models
  3. class Board(models.Model):
  4. pieces = ArrayField(ArrayField(models.IntegerField()))
  5. # Valid
  6. Board(
  7. pieces=[
  8. [2, 3],
  9. [2, 1],
  10. ]
  11. )
  12. # Not valid
  13. Board(
  14. pieces=[
  15. [2, 3],
  16. [2],
  17. ]
  18. )

If irregular shapes are required, then the underlying field should be made nullable and the values padded with None.

Querying ArrayField

There are a number of custom lookups and transforms for ArrayField. We will use the following example model:

  1. from django.contrib.postgres.fields import ArrayField
  2. from django.db import models
  3. class Post(models.Model):
  4. name = models.CharField(max_length=200)
  5. tags = ArrayField(models.CharField(max_length=200), blank=True)
  6. def __str__(self):
  7. return self.name

contains

The contains lookup is overridden on ArrayField. The returned objects will be those where the values passed are a subset of the data. It uses the SQL operator @>. For example:

  1. >>> Post.objects.create(name="First post", tags=["thoughts", "django"])
  2. >>> Post.objects.create(name="Second post", tags=["thoughts"])
  3. >>> Post.objects.create(name="Third post", tags=["tutorial", "django"])
  4. >>> Post.objects.filter(tags__contains=["thoughts"])
  5. <QuerySet [<Post: First post>, <Post: Second post>]>
  6. >>> Post.objects.filter(tags__contains=["django"])
  7. <QuerySet [<Post: First post>, <Post: Third post>]>
  8. >>> Post.objects.filter(tags__contains=["django", "thoughts"])
  9. <QuerySet [<Post: First post>]>

contained_by

This is the inverse of the 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:

  1. >>> Post.objects.create(name="First post", tags=["thoughts", "django"])
  2. >>> Post.objects.create(name="Second post", tags=["thoughts"])
  3. >>> Post.objects.create(name="Third post", tags=["tutorial", "django"])
  4. >>> Post.objects.filter(tags__contained_by=["thoughts", "django"])
  5. <QuerySet [<Post: First post>, <Post: Second post>]>
  6. >>> Post.objects.filter(tags__contained_by=["thoughts", "django", "tutorial"])
  7. <QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>

overlap

Returns objects where the data shares any results with the values passed. Uses the SQL operator &&. For example:

  1. >>> Post.objects.create(name="First post", tags=["thoughts", "django"])
  2. >>> Post.objects.create(name="Second post", tags=["thoughts", "tutorial"])
  3. >>> Post.objects.create(name="Third post", tags=["tutorial", "django"])
  4. >>> Post.objects.filter(tags__overlap=["thoughts"])
  5. <QuerySet [<Post: First post>, <Post: Second post>]>
  6. >>> Post.objects.filter(tags__overlap=["thoughts", "tutorial"])
  7. <QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
  8. >>> Post.objects.filter(tags__overlap=Post.objects.values_list("tags"))
  9. <QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>

Changed in Django 4.2:

Support for QuerySet.values() and values_list() as a right-hand side was added.

len

Returns the length of the array. The lookups available afterward are those available for IntegerField. For example:

  1. >>> Post.objects.create(name="First post", tags=["thoughts", "django"])
  2. >>> Post.objects.create(name="Second post", tags=["thoughts"])
  3. >>> Post.objects.filter(tags__len=1)
  4. <QuerySet [<Post: Second post>]>

Index transforms

Index transforms index into the array. Any non-negative integer can be used. There are no errors if it exceeds the size of the array. The lookups available after the transform are those from the base_field. For example:

  1. >>> Post.objects.create(name="First post", tags=["thoughts", "django"])
  2. >>> Post.objects.create(name="Second post", tags=["thoughts"])
  3. >>> Post.objects.filter(tags__0="thoughts")
  4. <QuerySet [<Post: First post>, <Post: Second post>]>
  5. >>> Post.objects.filter(tags__1__iexact="Django")
  6. <QuerySet [<Post: First post>]>
  7. >>> Post.objects.filter(tags__276="javascript")
  8. <QuerySet []>

Note

PostgreSQL uses 1-based indexing for array fields when writing raw SQL. However these indexes and those used in slices use 0-based indexing to be consistent with Python.

Slice transforms

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:

  1. >>> Post.objects.create(name="First post", tags=["thoughts", "django"])
  2. >>> Post.objects.create(name="Second post", tags=["thoughts"])
  3. >>> Post.objects.create(name="Third post", tags=["django", "python", "thoughts"])
  4. >>> Post.objects.filter(tags__0_1=["thoughts"])
  5. <QuerySet [<Post: First post>, <Post: Second post>]>
  6. >>> Post.objects.filter(tags__0_2__contains=["thoughts"])
  7. <QuerySet [<Post: First post>, <Post: Second post>]>

Note

PostgreSQL uses 1-based indexing for array fields when writing raw SQL. However these slices and those used in indexes use 0-based indexing to be consistent with Python.

Multidimensional arrays with indexes and slices

PostgreSQL has some rather esoteric behavior when using indexes and slices 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.

CIText fields

class CIText(**options)

Deprecated since version 4.2.

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 CITextExtension operation to set up the citext extension in PostgreSQL before the first CreateModel migration operation.

If you’re using an ArrayField of CIText fields, you must add 'django.contrib.postgres' in your INSTALLED_APPS, otherwise field values will appear as strings like '{thoughts,django}'.

Several fields that use the mixin are provided:

class CICharField(**options)

Deprecated since version 4.2: CICharField is deprecated in favor of CharField(db_collation="…") with a case-insensitive non-deterministic collation.

class CIEmailField(**options)

Deprecated since version 4.2: CIEmailField is deprecated in favor of EmailField(db_collation="…") with a case-insensitive non-deterministic collation.

class CITextField(**options)

Deprecated since version 4.2: CITextField is deprecated in favor of TextField(db_collation="…") with a case-insensitive non-deterministic collation.

These fields subclass CharField, EmailField, and TextField, respectively.

max_length won’t be enforced in the database since citext behaves similar to PostgreSQL’s text type.

Case-insensitive collations

It’s preferable to use non-deterministic collations instead of the citext extension. You can create them using the CreateCollation migration operation. For more details, see Managing collations using migrations and the PostgreSQL documentation about non-deterministic collations.

HStoreField

class HStoreField(**options)

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).

To use this field, you’ll need to:

  1. Add 'django.contrib.postgres' in your INSTALLED_APPS.
  2. Set up the hstore extension in PostgreSQL.

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.

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 KeysValidator.

Querying HStoreField

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:

  1. from django.contrib.postgres.fields import HStoreField
  2. from django.db import models
  3. class Dog(models.Model):
  4. name = models.CharField(max_length=200)
  5. data = HStoreField()
  6. def __str__(self):
  7. return self.name

Key lookups

To query based on a given key, you can use that key as the lookup name:

  1. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
  2. >>> Dog.objects.create(name="Meg", data={"breed": "collie"})
  3. >>> Dog.objects.filter(data__breed="collie")
  4. <QuerySet [<Dog: Meg>]>

You can chain other lookups after key lookups:

  1. >>> Dog.objects.filter(data__breed__contains="l")
  2. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>

or use F() expressions to annotate a key value. For example:

  1. >>> from django.db.models import F
  2. >>> rufus = Dog.objects.annotate(breed=F("data__breed"))[0]
  3. >>> rufus.breed
  4. 'labrador'

If the key you wish to query by clashes with the name of another lookup, you need to use the hstorefield.contains lookup instead.

Note

Key transforms can also be chained with: contains, icontains, endswith, iendswith, iexact, regex, iregex, startswith, and istartswith lookups.

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.

contains

The contains lookup is overridden on 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:

  1. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador", "owner": "Bob"})
  2. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  3. >>> Dog.objects.create(name="Fred", data={})
  4. >>> Dog.objects.filter(data__contains={"owner": "Bob"})
  5. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>
  6. >>> Dog.objects.filter(data__contains={"breed": "collie"})
  7. <QuerySet [<Dog: Meg>]>

contained_by

This is the inverse of the 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:

  1. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador", "owner": "Bob"})
  2. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  3. >>> Dog.objects.create(name="Fred", data={})
  4. >>> Dog.objects.filter(data__contained_by={"breed": "collie", "owner": "Bob"})
  5. <QuerySet [<Dog: Meg>, <Dog: Fred>]>
  6. >>> Dog.objects.filter(data__contained_by={"breed": "collie"})
  7. <QuerySet [<Dog: Fred>]>

has_key

Returns objects where the given key is in the data. Uses the SQL operator ?. For example:

  1. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
  2. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  3. >>> Dog.objects.filter(data__has_key="owner")
  4. <QuerySet [<Dog: Meg>]>

has_any_keys

Returns objects where any of the given keys are in the data. Uses the SQL operator ?|. For example:

  1. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
  2. >>> Dog.objects.create(name="Meg", data={"owner": "Bob"})
  3. >>> Dog.objects.create(name="Fred", data={})
  4. >>> Dog.objects.filter(data__has_any_keys=["owner", "breed"])
  5. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>

has_keys

Returns objects where all of the given keys are in the data. Uses the SQL operator ?&. For example:

  1. >>> Dog.objects.create(name="Rufus", data={})
  2. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  3. >>> Dog.objects.filter(data__has_keys=["breed", "owner"])
  4. <QuerySet [<Dog: Meg>]>

keys

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 ArrayField. Uses the SQL function akeys(). For example:

  1. >>> Dog.objects.create(name="Rufus", data={"toy": "bone"})
  2. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  3. >>> Dog.objects.filter(data__keys__overlap=["breed", "toy"])
  4. <QuerySet [<Dog: Rufus>, <Dog: Meg>]>

values

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 ArrayField. Uses the SQL function avals(). For example:

  1. >>> Dog.objects.create(name="Rufus", data={"breed": "labrador"})
  2. >>> Dog.objects.create(name="Meg", data={"breed": "collie", "owner": "Bob"})
  3. >>> Dog.objects.filter(data__values__contains=["collie"])
  4. <QuerySet [<Dog: Meg>]>

Range Fields

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 psycopg 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 [) (see the PostgreSQL documentation for details about different bounds). The default bounds can be changed for non-discrete range fields (DateTimeRangeField and DecimalRangeField) by using the default_bounds argument.

IntegerRangeField

class IntegerRangeField(**options)

Stores a range of integers. Based on an IntegerField. Represented by an int4range in the database and a django.db.backends.postgresql.psycopg_any.NumericRange in Python.

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 [).

BigIntegerRangeField

class BigIntegerRangeField(**options)

Stores a range of large integers. Based on a BigIntegerField. Represented by an int8range in the database and a django.db.backends.postgresql.psycopg_any.NumericRange in Python.

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 [).

DecimalRangeField

class DecimalRangeField(default_bounds=’[)’, **options)

Stores a range of floating point values. Based on a DecimalField. Represented by a numrange in the database and a django.db.backends.postgresql.psycopg_any.NumericRange in Python.

  • default_bounds

    New in Django 4.1.

    Optional. The value of bounds for list and tuple inputs. The default is lower bound included, upper bound excluded, that is [) (see the PostgreSQL documentation for details about different bounds). default_bounds is not used for django.db.backends.postgresql.psycopg_any.NumericRange inputs.

DateTimeRangeField

class DateTimeRangeField(default_bounds=’[)’, **options)

Stores a range of timestamps. Based on a DateTimeField. Represented by a tstzrange in the database and a django.db.backends.postgresql.psycopg_any.DateTimeTZRange in Python.

  • default_bounds

    New in Django 4.1.

    Optional. The value of bounds for list and tuple inputs. The default is lower bound included, upper bound excluded, that is [) (see the PostgreSQL documentation for details about different bounds). default_bounds is not used for django.db.backends.postgresql.psycopg_any.DateTimeTZRange inputs.

DateRangeField

class DateRangeField(**options)

Stores a range of dates. Based on a DateField. Represented by a daterange in the database and a django.db.backends.postgresql.psycopg_any.DateRange in Python.

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 [).

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:

  1. from django.contrib.postgres.fields import IntegerRangeField
  2. from django.db import models
  3. class Event(models.Model):
  4. name = models.CharField(max_length=200)
  5. ages = IntegerRangeField()
  6. start = models.DateTimeField()
  7. def __str__(self):
  8. return self.name

We will also use the following example objects:

  1. >>> import datetime
  2. >>> from django.utils import timezone
  3. >>> now = timezone.now()
  4. >>> Event.objects.create(name="Soft play", ages=(0, 10), start=now)
  5. >>> Event.objects.create(
  6. ... name="Pub trip", ages=(21, None), start=now - datetime.timedelta(days=1)
  7. ... )

and NumericRange:

  1. >>> from django.db.backends.postgresql.psycopg_any 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
  1. >>> Event.objects.filter(ages__contains=NumericRange(4, 5))
  2. <QuerySet [<Event: Soft play>]>
contained_by
  1. >>> Event.objects.filter(ages__contained_by=NumericRange(0, 15))
  2. <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:

  1. >>> from django.db.backends.postgresql.psycopg_any import DateTimeTZRange
  2. >>> Event.objects.filter(
  3. ... start__contained_by=DateTimeTZRange(
  4. ... timezone.now() - datetime.timedelta(hours=1),
  5. ... timezone.now() + datetime.timedelta(hours=1),
  6. ... ),
  7. ... )
  8. <QuerySet [<Event: Soft play>]>
overlap
  1. >>> Event.objects.filter(ages__overlap=NumericRange(8, 12))
  2. <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.

  1. >>> Event.objects.filter(ages__fully_lt=NumericRange(11, 15))
  2. <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.

  1. >>> Event.objects.filter(ages__fully_gt=NumericRange(11, 15))
  2. <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.

  1. >>> Event.objects.filter(ages__not_lt=NumericRange(0, 15))
  2. <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.

  1. >>> Event.objects.filter(ages__not_gt=NumericRange(3, 10))
  2. <QuerySet [<Event: Soft play>]>
adjacent_to

The returned ranges share a bound with the passed range.

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

Querying using the bounds

Range fields support several extra lookups.

startswith

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

  1. >>> Event.objects.filter(ages__startswith=21)
  2. <QuerySet [<Event: Pub trip>]>
endswith

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

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

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

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

Returns objects that have inclusive or exclusive lower bounds, depending on the boolean value passed. Can be chained to valid lookups for a BooleanField.

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

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.

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

Returns objects that have inclusive or exclusive upper bounds, depending on the boolean value passed. Can be chained to valid lookups for a BooleanField.

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

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.

  1. >>> Event.objects.filter(ages__upper_inf=True)
  2. <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 psycopg provides a register_range() to allow use of custom range types.

class RangeField(**options)

Base class for model range fields.

class django.contrib.postgres.forms.BaseRangeField

Base class for form range fields.

  • base_field

    The form field to use.

  • range_type

    The range type to use.

Range operators

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). This class is meant as a convenient method to avoid typos. The operator names overlap with the names of corresponding lookups.

  1. class RangeOperators:
  2. EQUAL = "="
  3. NOT_EQUAL = "<>"
  4. CONTAINS = "@>"
  5. CONTAINED_BY = "<@"
  6. OVERLAPS = "&&"
  7. FULLY_LT = "<<"
  8. FULLY_GT = ">>"
  9. NOT_LT = "&>"
  10. NOT_GT = "&<"
  11. ADJACENT_TO = "-|-"

RangeBoundary() expressions

class RangeBoundary(inclusive_lower=True, inclusive_upper=False)

  • inclusive_lower

    If True (default), the lower bound is inclusive '[', otherwise it’s exclusive '('.

  • 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 ExclusionConstraint. See the PostgreSQL documentation for the full details.