mirror of
https://github.com/django/django.git
synced 2025-10-24 06:06:09 +00:00
Fixed #12734. Deferred fields will now be properly converted to python when accessed. Thanks, Alex Gaynor.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@12579 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
@@ -2,56 +2,12 @@
|
||||
Tests for field subclassing.
|
||||
"""
|
||||
|
||||
from django.core import serializers
|
||||
from django.db import models
|
||||
from django.utils.encoding import force_unicode
|
||||
from django.core import serializers
|
||||
from django.core.exceptions import FieldError
|
||||
|
||||
class Small(object):
|
||||
"""
|
||||
A simple class to show that non-trivial Python objects can be used as
|
||||
attributes.
|
||||
"""
|
||||
def __init__(self, first, second):
|
||||
self.first, self.second = first, second
|
||||
from fields import Small, SmallField, JSONField
|
||||
|
||||
def __unicode__(self):
|
||||
return u'%s%s' % (force_unicode(self.first), force_unicode(self.second))
|
||||
|
||||
def __str__(self):
|
||||
return unicode(self).encode('utf-8')
|
||||
|
||||
class SmallField(models.Field):
|
||||
"""
|
||||
Turns the "Small" class into a Django field. Because of the similarities
|
||||
with normal character fields and the fact that Small.__unicode__ does
|
||||
something sensible, we don't need to implement a lot here.
|
||||
"""
|
||||
__metaclass__ = models.SubfieldBase
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
kwargs['max_length'] = 2
|
||||
super(SmallField, self).__init__(*args, **kwargs)
|
||||
|
||||
def get_internal_type(self):
|
||||
return 'CharField'
|
||||
|
||||
def to_python(self, value):
|
||||
if isinstance(value, Small):
|
||||
return value
|
||||
return Small(value[0], value[1])
|
||||
|
||||
def get_db_prep_save(self, value):
|
||||
return unicode(value)
|
||||
|
||||
def get_db_prep_lookup(self, lookup_type, value):
|
||||
if lookup_type == 'exact':
|
||||
return force_unicode(value)
|
||||
if lookup_type == 'in':
|
||||
return [force_unicode(v) for v in value]
|
||||
if lookup_type == 'isnull':
|
||||
return []
|
||||
raise FieldError('Invalid lookup type: %r' % lookup_type)
|
||||
|
||||
class MyModel(models.Model):
|
||||
name = models.CharField(max_length=10)
|
||||
@@ -60,6 +16,9 @@ class MyModel(models.Model):
|
||||
def __unicode__(self):
|
||||
return force_unicode(self.name)
|
||||
|
||||
class DataModel(models.Model):
|
||||
data = JSONField()
|
||||
|
||||
__test__ = {'API_TESTS': ur"""
|
||||
# Creating a model with custom fields is done as per normal.
|
||||
>>> s = Small(1, 2)
|
||||
|
||||
Reference in New Issue
Block a user