2
2
Tests for field subclassing.
5
from django.core import serializers
5
6
from django.db import models
6
7
from django.utils.encoding import force_unicode
7
from django.core import serializers
8
from django.core.exceptions import FieldError
12
A simple class to show that non-trivial Python objects can be used as
15
def __init__(self, first, second):
16
self.first, self.second = first, second
18
def __unicode__(self):
19
return u'%s%s' % (force_unicode(self.first), force_unicode(self.second))
22
return unicode(self).encode('utf-8')
24
class SmallField(models.Field):
26
Turns the "Small" class into a Django field. Because of the similarities
27
with normal character fields and the fact that Small.__unicode__ does
28
something sensible, we don't need to implement a lot here.
30
__metaclass__ = models.SubfieldBase
32
def __init__(self, *args, **kwargs):
33
kwargs['max_length'] = 2
34
super(SmallField, self).__init__(*args, **kwargs)
36
def get_internal_type(self):
39
def to_python(self, value):
40
if isinstance(value, Small):
42
return Small(value[0], value[1])
44
def get_db_prep_save(self, value):
47
def get_db_prep_lookup(self, lookup_type, value):
48
if lookup_type == 'exact':
49
return force_unicode(value)
50
if lookup_type == 'in':
51
return [force_unicode(v) for v in value]
52
if lookup_type == 'isnull':
54
raise FieldError('Invalid lookup type: %r' % lookup_type)
9
from fields import Small, SmallField, JSONField
56
12
class MyModel(models.Model):
57
13
name = models.CharField(max_length=10)
92
51
>>> MyModel.objects.filter(data__lt=s)
93
52
Traceback (most recent call last):
95
FieldError: Invalid lookup type: 'lt'
54
TypeError: Invalid lookup type: 'lt'
97
56
# Serialization works, too.
98
57
>>> stream = serializers.serialize("json", MyModel.objects.all())