fields.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import collections
  2. from django.db import models
  3. class CommaSeparatedList(list):
  4. """ str representation is useful for displayint in forms
  5. """
  6. def __str__(self):
  7. return ','.join(self)
  8. class CommaSeparatedCharField(models.CharField):
  9. "Implements comma-separated storage of lists"
  10. def from_db_value(self, value, expression, connection, context):
  11. if value is None:
  12. return value
  13. return CommaSeparatedList(value.split(','))
  14. def to_python(self, value):
  15. if isinstance(value, CommaSeparatedList):
  16. return value
  17. elif isinstance(value, collections.Iterable):
  18. return CommaSeparatedList(value)
  19. elif value is None:
  20. return value
  21. return CommaSeparatedList([i.strip() for i in value.split(',')])
  22. def clean(self, *args, **kwargs):
  23. return super().clean(*args, **kwargs)
  24. def get_prep_value(self, value):
  25. if isinstance(value, collections.Iterable):
  26. return ','.join(value)
  27. else:
  28. return value