python 未在DRF的perform_create函数内调用自定义确认函数

eblbsuwk  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(157)

这是我的准则。

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)

这是我的序列化器:

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

问题是,当我在ViewSet的perform_create()中调用自定义验证函数时,它没有被调用。
问题出在哪里?

6jjcrrmo

6jjcrrmo1#

validate成员函数应该在序列化器类的作用域中定义,而不是在class Meta内部。因此,需要左缩进函数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

相关问题