pythondjangodjango-rest-frameworkdjango-serializerdjango-validation

Custom Validate function is not being called inside perform_create function in DRF


This is my code.

class MyViewSet(ModelViewSet):
    serializer_class = MySerializer
    queryset = MyClass.objects.all()

    def get_serializer_class(self):
        if request.user.is_superuser:
            return self.serializer_class
        else:
            return OtherSerializer

    def perform_create(self, serializer):
        if request.user.is_superuser:
            if serializer.is_valid(): 
                serializer.save(organization=self.request.user.organization) 

        else:
            employee = Employee.objects.get(user=self.request.user)
            serializer.save(employee=employee, organization=self.request.user.organization) 

This is my Serializer:

class MySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.MyClass

        def validate(self, data):  
            employee = data.get('employee')
            members = Team.objects.get(id=team.id.members.all())
            if employee not in members:
                raise serializers.ValidationError('Invalid')
            return data  

The issue is, My custom validate function is not being called when I call it inside perform_create() in my ViewSet.

What might be the issue?


Solution

  • validate member function should be defined in the scope of the serializer class not inside class Meta. So you need to left-indent the function validate:

    class MySerializer(serializers.ModelSerializer):
        class Meta:
            model = models.MyClass
    
        def validate(self, data):  
            employee = data.get('employee')
            members = Team.objects.get(id=team.id.members.all())
            if employee not in members:
                raise serializers.ValidationError('Invalid')
            return data