class ArrayField(base_field, size=None, **options)
[source]
A field for storing lists of data. Most field types can be used, you simply 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 anIntegerField
or aCharField
. Most field types are permitted, with the exception of those handling relational data (ForeignKey
,OneToOneField
andManyToManyField
).It is possible to nest array fields - you can specify an instance of
ArrayField
as thebase_field
. For example:from django.db import models from django.contrib.postgres.fields import ArrayField class ChessBoard(models.Model): board = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, )
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:
from django.contrib.postgres.fields import ArrayField from django.db import models 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
.
Please login to continue.