Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Model field for storing a list of floats?

I want to store a variable-length list of floats in Django. There is the CommaSeparatedIntegerField, but is there anything like this that I could use? Would it be best to just implement my own CommaSeparetedFloatField or is there something that I am missing completely? Thanks.

like image 502
jairajs89 Avatar asked Aug 03 '10 14:08

jairajs89


1 Answers

I think you can define your own field quite easily:

comma_separated_float_list_re = re.compile('^([-+]?\d*\.?\d+[,\s]*)+$')
validate_comma_separated_float_list = RegexValidator(
              comma_separated_float_list_re, 
              _(u'Enter only floats separated by commas.'), 'invalid')

class CommaSeparatedFloatField(CharField):
    default_validators = [validators.validate_comma_separated_float_list]
    description = _("Comma-separated floats")

    def formfield(self, **kwargs):
        defaults = {
            'error_messages': {
                'invalid': _(u'Enter only floats separated by commas.'),
            }
        }
        defaults.update(kwargs)
        return super(CommaSeparatedFloatField, self).formfield(**defaults)

This snippet is not testet but maybe you can adapt it for your needs.

like image 187
Reto Aebersold Avatar answered Oct 04 '22 08:10

Reto Aebersold