DestroyAPIView Django休息验证

时间:2018-04-30 04:49:35

标签: django django-rest-framework

class DeleteLedgerCategory(DestroyAPIView):
    serializer_class = CategorySerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = Category.objects.filter(company = self.request.user.currently_activated_company, id=self.kwargs['pk'])
        return queryset

    def preform_destroy(self, instance):
        if instance.is_default == True:
            raise ValueError("Cannot delete default system category")
        return instance.delete()

在上面的基于类的视图中。我需要添加自定义验证错误消息。即。 if instance.is_default == True:引发错误...并且只允许在没有错误遇到时删除实例。如果有任何不明确的问题。做评论

2 个答案:

答案 0 :(得分:3)

您可以使用destroy方法自定义响应,而不仅仅是引发错误:

from rest_framework.response import Response

class DeleteLedgerCategory(DestroyAPIView):
    serializer_class = CategorySerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = Category.objects.filter(company = self.request.user.currently_activated_company, id=self.kwargs['pk'])
        return queryset

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.is_default == True:
            return Response("Cannot delete default system category", status=status.HTTP_400_BAD_REQUEST)
        self.perform_destroy(instance)

答案 1 :(得分:0)

尝试覆盖序列化器的验证方法,

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        # fields

    def validate_is_default(self, attrs):
        if attrs['is_default '] is True
            raise serializers.ValidationError("error message")
        return attrs


而你的views.py将是,

from rest_framework.response import Response


class DeleteLedgerCategory(DestroyAPIView):
    serializer_class = CategorySerializer
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = Category.objects.filter(company=self.request.user.currently_activated_company, id=self.kwargs['pk'])
        return queryset

    def preform_destroy(self, instance):
        serializer = CategorySerializer(data=self.get_queryset())
        serializer.is_valid(True)
        return instance.delete()