add south introspection, add json helper to load/dump time_struct
This commit is contained in:
parent
b5dd494e6f
commit
aa7f808431
1 changed files with 29 additions and 4 deletions
|
@ -1,7 +1,26 @@
|
|||
import time
|
||||
|
||||
from django.db import models
|
||||
from django.utils import simplejson as json
|
||||
|
||||
|
||||
def to_json(python_object):
|
||||
if isinstance(python_object, time.struct_time):
|
||||
return {'__class__': 'time.asctime',
|
||||
'__value__': time.asctime(python_object)}
|
||||
if isinstance(python_object, bytes):
|
||||
return {'__class__': 'bytes',
|
||||
'__value__': list(python_object)}
|
||||
raise TypeError(repr(python_object) + ' is not JSON serializable')
|
||||
|
||||
def from_json(json_object):
|
||||
if '__class__' in json_object:
|
||||
if json_object['__class__'] == 'time.asctime':
|
||||
return time.strptime(json_object['__value__'])
|
||||
if json_object['__class__'] == 'bytes':
|
||||
return bytes(json_object['__value__'])
|
||||
return json_object
|
||||
|
||||
class DictField(models.TextField):
|
||||
"""DictField is a textfield that contains JSON-serialized dictionaries."""
|
||||
|
||||
|
@ -13,7 +32,7 @@ class DictField(models.TextField):
|
|||
if isinstance(value, dict):
|
||||
return value
|
||||
try:
|
||||
value = json.loads(value)
|
||||
value = json.loads(value, object_hook=from_json)
|
||||
except: #this is required to load fixtures
|
||||
value = eval(value)
|
||||
assert isinstance(value, dict)
|
||||
|
@ -22,7 +41,7 @@ class DictField(models.TextField):
|
|||
def get_db_prep_save(self, value):
|
||||
"""Convert our JSON object to a string before we save"""
|
||||
assert isinstance(value, dict)
|
||||
value = json.dumps(value)
|
||||
value = json.dumps(value, default=to_json)
|
||||
return super(DictField, self).get_db_prep_save(value)
|
||||
|
||||
class TupleField(models.TextField):
|
||||
|
@ -37,7 +56,7 @@ class TupleField(models.TextField):
|
|||
return value
|
||||
|
||||
try:
|
||||
value = json.loads(value)
|
||||
value = json.loads(value, object_hook=from_json)
|
||||
except: #this is required to load fixtures
|
||||
value = eval(value)
|
||||
assert isinstance(value, list)
|
||||
|
@ -46,6 +65,12 @@ class TupleField(models.TextField):
|
|||
def get_db_prep_save(self, value):
|
||||
"""Convert our JSON object to a string before we save"""
|
||||
assert isinstance(value, tuple)
|
||||
value = json.dumps(value)
|
||||
value = json.dumps(value, default=to_json)
|
||||
return super(TupleField, self).get_db_prep_save(value)
|
||||
|
||||
try:
|
||||
from south.modelsinspector import add_introspection_rules
|
||||
add_introspection_rules([], ["^oxdjango\.fields\.DictField"])
|
||||
add_introspection_rules([], ["^oxdjango\.fields\.TupleField"])
|
||||
except:
|
||||
pass
|
||||
|
|
Loading…
Reference in a new issue