mirror of
https://github.com/django/django.git
synced 2024-12-28 12:06:22 +00:00
c5ef65bcf3
* Renamed smart_unicode to smart_text (but kept the old name under Python 2 for backwards compatibility). * Renamed smart_str to smart_bytes. * Re-introduced smart_str as an alias for smart_text under Python 3 and smart_bytes under Python 2 (which is backwards compatible). Thus smart_str always returns a str objects. * Used the new smart_str in a few places where both Python 2 and 3 want a str.
78 lines
2.1 KiB
Python
78 lines
2.1 KiB
Python
from __future__ import unicode_literals
|
|
|
|
import json
|
|
|
|
from django.db import models
|
|
from django.utils.encoding import force_text
|
|
from django.utils import six
|
|
|
|
|
|
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
|
|
|
|
def __unicode__(self):
|
|
return '%s%s' % (force_text(self.first), force_text(self.second))
|
|
|
|
def __str__(self):
|
|
return six.text_type(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, connection):
|
|
return six.text_type(value)
|
|
|
|
def get_prep_lookup(self, lookup_type, value):
|
|
if lookup_type == 'exact':
|
|
return force_text(value)
|
|
if lookup_type == 'in':
|
|
return [force_text(v) for v in value]
|
|
if lookup_type == 'isnull':
|
|
return []
|
|
raise TypeError('Invalid lookup type: %r' % lookup_type)
|
|
|
|
class SmallerField(SmallField):
|
|
pass
|
|
|
|
|
|
class JSONField(models.TextField):
|
|
__metaclass__ = models.SubfieldBase
|
|
|
|
description = ("JSONField automatically serializes and desializes values to "
|
|
"and from JSON.")
|
|
|
|
def to_python(self, value):
|
|
if not value:
|
|
return None
|
|
|
|
if isinstance(value, six.string_types):
|
|
value = json.loads(value)
|
|
return value
|
|
|
|
def get_db_prep_save(self, value, connection):
|
|
if value is None:
|
|
return None
|
|
return json.dumps(value)
|