django serializers to json - custom json output format

前端 未结 4 581
野的像风
野的像风 2021-02-04 19:23

I am quite new to django and recently I have a requirement of a JSON output, for which I use the following django code:

data = serializers.serialize(\"json\", My         


        
4条回答
  •  故里飘歌
    2021-02-04 19:58

    You'll need to write a custom Json serializer. Something like this should do the trick:

    class FlatJsonSerializer(Serializer):
        def get_dump_object(self, obj):
            data = self._current
            if not self.selected_fields or 'id' in self.selected_fields:
                data['id'] = obj.id
            return data
    
        def end_object(self, obj):
            if not self.first:
                self.stream.write(', ')
            json.dump(self.get_dump_object(obj), self.stream,
                      cls=DjangoJSONEncoder)
            self._current = None
    
        def start_serialization(self):
            self.stream.write("[")
    
        def end_serialization(self):
            self.stream.write("]")
    
        def getvalue(self):
            return super(Serializer, self).getvalue()
    

    The you can use it like this:

    s = FlatJsonSerializer()
    s.serialize(MyModel.objects.all())
    

    Or you could register the serializer with django.core.serializers.register_serializer and then use the familiar serializers.serialize shortcut.

    Take a look at the django implementation as a reference if you need further customization: https://github.com/django/django/blob/master/django/core/serializers/json.py#L21-62

提交回复
热议问题