Is it possible to store an array in Django model? Is it possible to store an array in Django model? arrays arrays

Is it possible to store an array in Django model?


I'd have two advices for you:

1) Use ArrayField if you are using PostgreSQL as your database. You can read more about ArrayField here.

2) Encode your array as JSON and store it either as a plain string or using a JSONField as found here.

I'd personally prefer option number 1 since that is the cleaner and nicer way but depending on what you are actually using to store your data that might not be available to you.


Yes, you can use it like this:

from django.contrib.postgres.fields import ArrayFieldclass Board(models.Model):    pieces = ArrayField(ArrayField(models.IntegerField()))

However, it can only be available when using PostgreSQL for the database.


If you aren't using Postgres, I recommend Django's validate_comma_separated_integer_list validator.

https://docs.djangoproject.com/en/dev/ref/validators/#django.core.validators.validate_comma_separated_integer_list

You use is as a validator on a CharField().