fields.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import json
  2. from django.db import models
  3. from django.utils.encoding import force_unicode
  4. class Small(object):
  5. """
  6. A simple class to show that non-trivial Python objects can be used as
  7. attributes.
  8. """
  9. def __init__(self, first, second):
  10. self.first, self.second = first, second
  11. def __unicode__(self):
  12. return u'%s%s' % (force_unicode(self.first), force_unicode(self.second))
  13. def __str__(self):
  14. return unicode(self).encode('utf-8')
  15. class SmallField(models.Field):
  16. """
  17. Turns the "Small" class into a Django field. Because of the similarities
  18. with normal character fields and the fact that Small.__unicode__ does
  19. something sensible, we don't need to implement a lot here.
  20. """
  21. __metaclass__ = models.SubfieldBase
  22. def __init__(self, *args, **kwargs):
  23. kwargs['max_length'] = 2
  24. super(SmallField, self).__init__(*args, **kwargs)
  25. def get_internal_type(self):
  26. return 'CharField'
  27. def to_python(self, value):
  28. if isinstance(value, Small):
  29. return value
  30. return Small(value[0], value[1])
  31. def get_db_prep_save(self, value, connection):
  32. return unicode(value)
  33. def get_prep_lookup(self, lookup_type, value):
  34. if lookup_type == 'exact':
  35. return force_unicode(value)
  36. if lookup_type == 'in':
  37. return [force_unicode(v) for v in value]
  38. if lookup_type == 'isnull':
  39. return []
  40. raise TypeError('Invalid lookup type: %r' % lookup_type)
  41. class SmallerField(SmallField):
  42. pass
  43. class JSONField(models.TextField):
  44. __metaclass__ = models.SubfieldBase
  45. description = ("JSONField automatically serializes and desializes values to "
  46. "and from JSON.")
  47. def to_python(self, value):
  48. if not value:
  49. return None
  50. if isinstance(value, basestring):
  51. value = json.loads(value)
  52. return value
  53. def get_db_prep_save(self, value, connection):
  54. if value is None:
  55. return None
  56. return json.dumps(value)