Django: A model field for storing a list of floats?

I want to save a variable-length list of variables in Django. There is a CommaSeparatedIntegerField, but is there anything similar that I could use? Would it be best to implement my own CommaSeparetedFloatField or is there something I am completely missing? Thank.

+3
source share
2 answers

I think you can easily define your field:

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 test, but maybe you can adapt it to your needs.

+5
source

. , CharField . , , - , .

, , , PickledObjectField (, ) BinaryField.

The PickledObjectField , , , , , .

BinaryField - , , / . , , , . struct .

0

Source: https://habr.com/ru/post/1757830/


All Articles