django serializers to json - custom json output format

前端 未结 4 580
野的像风
野的像风 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 20:13

    I just came across this as I was having the same problem. I also solved this with a custom serializer, tried the "EDIT 1" method but it didn't work too well as it stripped away all the goodies that the django JSON encoder already did (decimal, date serialization), which you can rewrite it yourself but why bother. I think a much less intrusive way is to inherit the JSON serializer directly like this.

    from django.core.serializers.json import Serializer
    from django.utils.encoding import smart_text    
    
    class MyModelSerializer(Serializer):
        def get_dump_object(self, obj):
            self._current['id'] = smart_text(obj._get_pk_val(), strings_only=True)
            return self._current
    

    Sso the main culprit that writes the fields and model thing is at the parent level python serializer and this way, you also automatically get the fields filtering that's already built into django's JSON serializer. Call it like this

    serializer = MyModelSerializer()
    data = serializer.serialize(, fields=('field1', 'field2'))
    

提交回复
热议问题