Django RF,验证反馈方法.(return Response vs raise ValidationError)



当我在Django查询集中进行验证时,以下代码成功执行,如果查询不满足某些参数,则返回验证错误

if second_condition:
raise ValidationError("1 error")
else:
serializer.save()

同时,以下代码未能按预期给出响应1 error

if second_condition:
return Response("1 error")
else:
serializer.save()

为什么会这样?

注意:避免缩进格式

下面给出的不带格式的完整代码

class CommentCreate(generics.CreateAPIView):
serializer_class = CommentSerializer
queryset = Comment.objects.all()
permission_classes = [IsAuthenticated]
def perform_create(self, serializer):
request_user = self.request.user
pk = self.kwargs.get('pk')
product = get_object_or_404(Product, pk=pk)
if Po.objects.filter(Q(user=request_user) & Q(item_id=pk) & Q(delivered=True)).exists():
if Comment.objects.filter(Q(author=request_user) & Q(product=product)).exists():
raise ValidationError("You have already commented")
else:
serializer.save(author=request_user, product=product)
else:
raise ValidationError("Purchase this item,prior to commenting")

这是因为异常在堆栈中冒泡,直到异常被DRF捕获并按预期处理,而返回仅返回钩子perform_create的值。您可以从主视图处理程序返回类似Response的实例(无论django或DRF中有什么(。关于这里的钩子,a没有检查返回值在那里的含义。

相关内容

最新更新