django serializers to json - custom json output format

前端 未结 4 577
野的像风
野的像风 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:53

    You can add 'fields' parameter to the serialize-function, like this:

    data = serializers.serialize('xml', SomeModel.objects.all(), fields=('name','size'))
    

    See: https://docs.djangoproject.com/en/dev/topics/serialization/

    EDIT 1:

    You can customize the serializer to get only the fields you specify.

    From Override Django Object Serializer to get rid of specified model:

    from django.core.serializers.python import Serializer
    
    class MySerialiser(Serializer):
        def end_object( self, obj ):
            self._current['id'] = obj._get_pk_val()
            self.objects.append( self._current )
    
     # views.py
     serializer = MySerialiser()
     data = serializer.serialize(some_qs)
    

提交回复
热议问题