Django Model自定义序列化为JSON

时间:2014-08-12 04:49:24

标签: python json django serialization

默认的串行器实现:

class Serializer(base.Serializer):
    """
    Serializes a QuerySet to basic Python objects.
    """

    internal_use_only = True

    def start_serialization(self):
        self._current = None
        self.objects = []

    def end_serialization(self):
        pass

    def start_object(self, obj):
        self._current = {}

    def end_object(self, obj):
        self.objects.append({
            "model"  : smart_unicode(obj._meta),
            "pk"     : smart_unicode(obj._get_pk_val(), strings_only=True),
            "fields" : self._current
        })
        self._current = None

数据输出格式:

[{" pk":2," model":" android.job"," fields":{"状态":" lol","客户":"哈哈"}},{" pk":3," model":" android.job"," fields":{" status":" lul"," customer&# 34;:" BWAHA"}}]

我的压倒一切:

class MySerialiser(Serializer):
    def start_serialization(self):
        self._current = None
        self.objects = []

    def end_serialization(self):
        pass

    def start_object(self, obj):
        self._current = {}

    def end_object(self, obj):
        self._current['id'] = obj._get_pk_val()
        self.objects.append(self._current)

输出格式:

{" status":" lol"," customer":" HAHA",id:2L} {" status& #34;:" lul","客户":" BWAHA",id:3L}

我需要什么:

[{" status":" lol"," customer":" HAHA",id:2L},{&#34 ;状态":" lul","客户":" BWAHA",id:3L}]

注意 - 这是在Django中 - 所有这些都是String类型!不要认为它们是列表/词组

1 个答案:

答案 0 :(得分:0)

这终于奏效了!

class MySerialiser(Serializer):
    def start_serialization(self):
        self._current = None
        self.objects = []

    def end_serialization(self):
        simplejson.dump(self.objects, self.stream, cls=DjangoJSONEncoder, **self.options)

    def getvalue(self):
        if callable(getattr(self.stream, 'getvalue', None)):
            return self.stream.getvalue()

    def start_object(self, obj):
        self._current = {}

    def end_object(self, obj):
        self._current['id'] = obj._get_pk_val()
        self.objects.append(self._current)
        self._current = None