Skip to main content

Custom Django model field to store multiple values.

Project description

A reusable Django model field to store collections. Ported for django 3 and python 3. You can find the original here:


  • highly configurable model field (changing collection and item types, sorting, choices, item uniqueness and more)
  • custom lookups to simplify queries over collection items
  • form fields for working with collections
  • collection item validators
  • extended get_FIELD_display method for model fields with choices
  • works with database backends without native support for multi-value columns (like ArrayField for PostgreSQL)


pip install django3-collectionfield


Model field

Define model with field that stores lists of strings:

from django.db import models
from collectionfield.models import CollectionField

class MyModel(models.Model):
    tags = CollectionField()

Pass values to model field:

my_model = MyModel.objects.create(tags=['test', 'values'])
['test', 'values']

Making queries

Retrieve model instances with particular value present in the collection:


Retrieve model instances with ALL values present in the collection (ignoring items’ order):

MyModel.objects.filter(tags__hasall=['test', 'values'])

Retrieve model instances with ANY of values present in the collection:

MyModel.objects.filter(tags__hasany=['test', 'values'])

Customizing collections

Custom collection and item type:

class IntegerSet(models.Model):
    # This field will provide sets of integers
    # instead of default lists of strings:
    values = CollectionField(collection_type=set, item_type=int)

Sorting and uniqueness:

class SortedUniqueTextList(models.Model):
    # Before saving, items will be sorted and duplicates dropped:
    texts = CollectionField(sort=True, unique_items=True)

Choices and collection size limit:

class TaggedModel(models.Model):
    tags = CollectionField(
        # Both choices and max_items limit are checked during model validation.
            ('action', "Action"),
            ('comedy', "Comedy"),
            ('horror', "Horror"),
            # ...

get_FIELD_display method can handle multiple choices and provide options to customize the display:

tagged_model = TaggedModel.objects.create(tags=['action', 'horror'])
"Action, Horror"

def li_mapper(value, label):
    return "<li>{0}</li>".format(label)

def ul_wrapper(field_display):
    return "<ul>{0}</ul>".format(field_display)

tagged_model.get_tags_display(delimiter='', mapper=li_mapper, wrapper=ul_wrapper)

Django built-in validators work with entire field values. django3-collectionfield provide validation of single collection items:

from collectionfield.validators import (
    ItemMinValueValidator, ItemMaxValueValidator

class IntegerList(models.Model):
    values = CollectionField(
        # item validators check each item separately:
        validators=[ItemMinValueValidator(1), ItemMaxValueValidator(5)]

Form fields

django-collectionfield comes with 2 form fields:

from collectionfield.forms import CollectionField, CollectionChoiceField

# ``collectionfield.forms.CollectionField`` converts comma-separated text
# into collection of values:

class MyForm(forms.Form):
    values = CollectionField()

my_form = MyForm({'values': "A, B, C"})
['A', 'B', 'C']

# ``collectionfield.forms.CollectionChoiceField`` behaves more like
# regular MultipleChoiceField:

class MyChoiceForm(forms.Form):
   values = CollectionChoiceField(
           ('action', "Action"),
           ('comedy', "Comedy"),
           ('horror', "Horror"),
           # ...

my_choice_form = MyChoiceForm({'values': ['action', 'comedy']})
['action', 'comedy']

Both form fields support the same set of parameters as the model field:

from collectionfield.forms import CollectionField

class MyForm(forms.Form):
    values = CollectionField(collection_type=set, item_type=int)

my_form = MyForm({'values': "1, 2, 1, 3"})
{1, 2, 3}

Representation in database

CollectionField converts its values into string of up to 1024 characters using the following format:


Default delimiter (‘|’) and maximum length can be configured:

class MyModel(models.Model):
    values = CollectionField(delimiter="$", max_length=2000)


Python: 3.5

Django: 3

Project details

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for django3-collectionfield, version 1.0.0
Filename, size File type Python version Upload date Hashes
Filename, size django3_collectionfield-1.0.0-py3-none-any.whl (18.0 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size django3-collectionfield-1.0.0.tar.gz (17.7 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page