/tests/modeltests/field_subclassing/fields.py

https://code.google.com/p/mango-py/ · Python · 76 lines · 54 code · 17 blank · 5 comment · 8 complexity · 63a6ca5c6361ad091bfaf8ffd03cb6be MD5 · raw file

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