这是我的准则。
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()中调用自定义验证函数时,它没有被调用。
问题出在哪里?
1条答案
按热度按时间6jjcrrmo1#
validate
成员函数应该在序列化器类的作用域中定义,而不是在class Meta
内部。因此,需要左缩进函数validate
: