Home > Enterprise >  DRF- how to return field which is not included in model in response
DRF- how to return field which is not included in model in response

Time:07-02

I have view:

class SomeView(APIView):
   def get(self,request):
   serializer = serializers.SomeViewSerializer
   return Response({'result_url': ???})

and serializer:

class SomeViewSerializer(serializers.Serializer):
   url = serializers.SerializerMethodField()

   def get_url(self):
      res_id = genetare_url(self.id)
      return res_id

in this case url is not part of any model, but I want to return only this (result of get_url) in response, but I couldn't figure out how to write it in view above. any help will be appriciated, thank you

CodePudding user response:

You can simply call the serializer's method.

class SomeView(APIView):
   def get(self, request):
       serializer = serializers.SomeViewSerializer()
       return Response({'result_url': serializer.get_url()})

CodePudding user response:

Try this one. Add class Meta: in Serializer

class SomeViewSerializer(serializers.Serializer):
   url = serializers.SerializerMethodField()

   class Meta:
        fields = ('url')

   def get_url(self):
      res_id = genetare_url(self.id)
      return res_id

and view like this:

class SomeView(APIView):
    def get(self,request):
        serializer = serializers.SomeViewSerializer
        return Response(serializer.data)
  • Related