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.
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.
It depends a bit on your use case. If you get the list of floats as a string and never need the values themselves, subclassing CharField is reasonable. However, it's not especially space-efficient and you have to do a conversion if you want to do anything with the numbers other than display them.
If you have long lists of floats, often need to lookup, use, or modify their values, and are trying to save DB space, you could consider either using a PickledObjectField or writing the floats to a binary string (like writing to a binary file), and storing that binary string using BinaryField.
The PickledObjectField is overkill, but if you might change the structure of this object later or put in things that are not floats, it's probably the way to go.
The BinaryField is the one that stores the numbers in a form closest to their raw / intrinsic forms. That means it should have the most compact storage, fastest lookups & conversions, and fewest errors with rounding or conversion. The struct package gives functions for converting to and from binary strings.
精彩评论