If you look at the try/except block under is_valid() method, I'm trying to check if an object exists and if so, return a 202 error. My question is can I directly return a a response from the serializer or do I need to raise a specific exception and then handle the exception in the views?
class CreateJobSerializer(GenericSerializer):
    class Meta:
        model = Job
        fields = ('name',)
        validators = []
    def is_valid(self, raise_exception=False):
        if hasattr(self, 'initial_data'):
            super(CreateJobSerializer, self).clean_ids()
            try:
                Job.objects.get(name=self.initial_data['name'])
                return Response(serializer.errors, status=status.HTTP_202_ACCEPTED)
            except:
                return super().is_valid(raise_exception)
First of all HTTP_202 is not an error status. The description for 202 is
The request has been accepted for processing, but the processing has not been completed.
You can do such type of validations directly from the serializer. For example
class CreateJobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job
        fields = ('name',)
    def validate_name(self, value):
        if Job.objects.filter(name=value).exists():
            raise serializers.ValidationError("Name already exist")
        return value
If you still want to use HTTP_202 then Create new exception by inheriting default APIException and override status_code to 202. Now raise the new exception.
from rest_framework.exceptions import APIException
class APIException202(APIException):
    status_code = 202
class CreateJobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job
        fields = ('name',)
    def validate_name(self, value):
        if Job.objects.filter(name=value).exists():
            raise APIException202("Name already exist")
        return value
And in view use is_valid method for validation
serializer = CreateJobSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.is_valid(raise_exception=True) will do the validation and raise errors with proper status code that you have defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With