[Django]-How do I use CommaSeparatedIntegerField in django?

23👍

Looking at the source for django…

class CommaSeparatedIntegerField(CharField):
    def formfield(self, **kwargs):
        defaults = {
            'form_class': forms.RegexField,
            'regex': '^[\d,]+$',
            'max_length': self.max_length,
            'error_messages': {
                'invalid': _(u'Enter only digits separated by commas.'),
            }
        }
        defaults.update(kwargs)
        return super(CommaSeparatedIntegerField, self).formfield(**defaults)

Check out that regex validator. Looks like as long as you give it a list of integers and commas, django won’t complain.

You can define it just like a charfield basically:

class Foo(models.Model):
    int_list = models.CommaSeparatedIntegerField(max_length=200)

And populate it like this:

f = Foo(int_list="1,2,3,4,5")

18👍

I would like to add that this Field is depricated in Django 1.9. In Django 1.9+ a CharField with validators=[validate_comma_separated_integer_list] should be used.

👤dsax7

15👍

Works for versions greater than Django 1.9

First Step:- Import this ( May change in newer versions , so double check that)

from django.core.validators import validate_comma_separated_integer_list

Second Step :- Write Field

class RestaurantLocation(models.Model):
    name = models.CharField(max_length=200)
    location = models.CharField(max_length=200,null=True,blank=True)
    category = models.CharField(max_length=200,null=True,blank=False)
    choices_field = models.CharField(validators=[validate_comma_separated_integer_list],max_length=200, blank=True, null=True,default='')
    def __str__(self):
        return self.name

Note: Please make sure to use default = '' if you are adding column to an already created database otherwise you would get the following option to choose after running python manage.py migrate


You are trying to add a non-nullable field 'choices_field' to restaurantlocation without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a 
null value for this column)
2) Quit, and let me add a default in models.py
Select an option: 

Happy Coding!

7👍

I just happened to have dealt with CommaSeparatedIntegerField in my latest project. I was using MySQL and it seemed like supplying a string of comma separated integer values is very DB friendly e.g. ‘1,2,3,4,5’. If you want to leave it blank, just pass an empty string.

It does act like a CharField, and beaved in a weird way for me.. I ended up with values like “[1, 2, 3, 4, 5]” including the brackets in my database! So watch out!

Leave a comment