我已经编写了一个自定义 Django 模型字段来存储dateutil.relativedelta
's. 该字段如下所示:
class RelativeDeltaField(models.CharField):
description = "Relative delta"
__metaclass__ = models.SubfieldBase
max_length = 200
def __init__(self, *args, **kwargs):
kwargs['max_length'] = self.max_length
super(RelativeDeltaField, self).__init__(*args, **kwargs)
def to_python(self, value):
if isinstance(value, relativedelta):
return value
try:
return eval(value)
except SyntaxError, e:
logging.error("Mangled data for a relativedelta field. Was the data truncated in MySQL column? Either manually fix, or change the next line to 'return None' and manually fix. value=%r message=%r" % (value, e))
raise
def get_db_prep_save(self, value, connection):
return repr(value)
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_prep_value(value)
我正在尝试将具有此字段的对象序列化为 json:
serializers.serialize('json', obj)
但我收到一个错误:
…
File "/home/rory/tix/virtualenv/lib/python2.6/site-packages/django/core/serializers/json.py", line 58, in default
return super(DjangoJSONEncoder, self).default(o)
File "/usr/lib/python2.6/dist-packages/simplejson/encoder.py", line 190, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: relativedelta(hours=+1) is not JSON serializable
通过使用pdb
,我可以看到o
在这种情况下是对象本身,它没有被转换为任何东西,也没有被序列化。
我该如何解决这个问题,以便我可以序列化我的字段?
Django 文档说(https://docs.djangoproject.com/en/dev/howto/custom-model-fields/#converting-field-data-for-serialization)添加 a value_to_string
,我确实有。