Django uses a field's
value_to_string
方法在序列化程序中提供字符串表示形式。因此,可以定义一个覆盖此方法的自定义字段子类:
class MyDateTimeField(DateTimeField)
def value_to_string(self, obj):
val = self._get_val_from_obj(obj)
if val is None:
data = ''
else:
data = val.isoformat()
return data
编辑
Aargh, looks like I was looking in completely the wrong place. 这个
serializers.python.Serializer.handle_field
方法实际上检查日期时间字段,并将其通过未更改的JSON编码器传递。所以我们需要重写的就是编码器。
class MyJSONEncoder(DjangoJSONEncoder):
def default(self, o):
if isinstance(o, datetime.datetime):
return o.isoformat()
else:
return super(MyJSONEncoder, self).default(o)
不幸的是,
wadofstuff
hardcodes the original DjangoJSONEncoder, so we'll need to override the serializer too.
from wadofstuff.django.serializers.json import Serializer
class BetterSerializer(Serializer):
"""
Convert a queryset to JSON.
"""
def end_serialization(self):
"""Output a JSON encoded queryset."""
self.options.pop('stream', None)
self.options.pop('fields', None)
self.options.pop('excludes', None)
self.options.pop('relations', None)
self.options.pop('extras', None)
simplejson.dump(self.objects, self.stream, cls=MyJSONEncoder,
**self.options)