Shijo Rose
Shijo Rose

Reputation: 213

Serializer Validate() method not invoking in serializer DRF

In DRF the serializer validate() method is not calling by default.

i am using the serializer like this:

class SampleListView(ListAPIView):
    queryset = Sample.objects.all()
    serializer_class = SampleSerializer
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response(sorted_result)

class SampleSerializer(serializers.ModelSerializer):
    custom_data = serializers.SerializerMethodField()

    class Meta:
        model = SampleModel
        fields = ('field_1', 'field_2')

    def validate(self, data):
        return data

Execution not enter into the validate() method in serializer.

Anyone have an idea about this?

Upvotes: 0

Views: 202

Answers (1)

Mohammed Aadil
Mohammed Aadil

Reputation: 153

Shijo Validate() only be called when you are using save method of serializer hence only be used for create and update method of API. As refer in Validation in DRF documentation

you always need to call is_valid() before attempting to access the validated data, or save an object instance.

Upvotes: 1

Related Questions