PageRenderTime 38ms CodeModel.GetById 33ms app.highlight 3ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/modeltests/field_subclassing/fields.py

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