What is the best way to store an array of integers in a django database?
(only for Django with Postgres DB)
You can use ArrayField with base_field IntegerField
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.
ArrayField(
models.IntegerField(),
blank=True, # Optional: allows the array to be empty
default=list # Default value is an empty list
)
From 2018
CommaSeparatedIntergerField
is no more available since Django 1.9:
Deprecated since version 1.9: This field is deprecated in favor of
CharField
with validators=[validate_comma_separated_integer_list].
By default it sets a comma separated integer list field.
Returns a RegexValidator instance that ensures a string consists of integers separated by sep. It allows negative integers when allow_negative is True.
from django.db import models
from django.core.validators import int_list_validator
class YourModel(models.Model):
....
....
int_list = models.CharField(validators=int_list_validator)
....