Storing an Integer Array in a Django Database

CommaSeparatedIntegerField comes to mind instantly. It is implemented as VARCHAR on most database backends. To be sure though, you may want to skim through django/db/backends/*.


CommaSeparatedIntergerField is no more available since Django 1.9:

From Docs:

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.

int_list_validator

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

I'm using ArrayField: https://docs.djangoproject.com/en/2.1/ref/contrib/postgres/fields/#querying-arrayfield

eg.

class Place(models.Model):
    nearby_places_ids = ArrayField(models.IntegerField(null=True, blank=True), null=True, blank=True)

with usage:

place.nearby_places_ids = [1,2,3]
place.save()

models.Place.objects.filter(nearby_places_ids__contains=[1])
<QuerySet [<Place: Hostel DIC>]>

models.Place.objects.filter(nearby_places_ids__contains=[1,2,3,4])
<QuerySet []>