2
Tests for field subclassing.
5
from django.db import models
6
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)
56
class MyModel(models.Model):
57
name = models.CharField(max_length=10)
58
data = SmallField('small field')
60
def __unicode__(self):
61
return force_unicode(self.name)
63
__test__ = {'API_TESTS': ur"""
64
# Creating a model with custom fields is done as per normal.
68
>>> m = MyModel(name='m', data=s)
71
# Custom fields still have normal field's attributes.
72
>>> m._meta.get_field('data').verbose_name
75
# The m.data attribute has been initialised correctly. It's a Small object.
76
>>> m.data.first, m.data.second
79
# The data loads back from the database correctly and 'data' has the right type.
80
>>> m1 = MyModel.objects.get(pk=m.pk)
81
>>> isinstance(m1.data, Small)
86
# We can do normal filtering on the custom field (and will get an error when we
87
# use a lookup type that does not make sense).
89
>>> s2 = Small('a', 'b')
90
>>> MyModel.objects.filter(data__in=[s, s1, s2])
92
>>> MyModel.objects.filter(data__lt=s)
93
Traceback (most recent call last):
95
FieldError: Invalid lookup type: 'lt'
97
# Serialization works, too.
98
>>> stream = serializers.serialize("json", MyModel.objects.all())
100
'[{"pk": 1, "model": "field_subclassing.mymodel", "fields": {"data": "12", "name": "m"}}]'
101
>>> obj = list(serializers.deserialize("json", stream))[0]
105
# Test retrieving custom field data
107
>>> m1 = MyModel(name="1", data=Small(1, 2))
109
>>> m2 = MyModel(name="2", data=Small(2, 3))
111
>>> for m in MyModel.objects.all(): print unicode(m.data)