如何验证DRF中的URL变量(django rest框架)generic.listview



我想在drf generic.ListView中使用我的queryset的URL变量,但是我现在可以验证它,现在我想知道如何验证

我编写了以下代码,但它不起作用。

class VideoView(generics.ListAPIView):
    def validate(self):
        print("ejra")
        if "class" not in self.request.GET:
            return Response({"error": "class should exist"}, status=status.HTTP_400_BAD_REQUEST)
        if len(Class.objects.filter(pk=self.request.GET["class"])) < 1:
            return Response({"error": "class not found"}, status=status.HTTP_400_BAD_REQUEST)
    def get_queryset(self):
        self.validate()
        class_obj = Class.objects.get(pk=self.request.GET["class"])
        queryset = Video.objects.filter(study_class=class_obj).order_by("-date")
        return queryset
    serializer_class = VideoSerializer

您可以从 validate() 方法本身提出 DRF API ValidationError

from rest_framework.exceptions import ValidationError

class VideoView(generics.ListAPIView):
    serializer_class = VideoSerializer
    def validate(self):
        if "class" not in self.request.GET:
            raise ValidationError({"error": "class should exist"})
        if Class.objects.filter(pk=self.request.GET["class"]).exists():
            raise ValidationError({"error": "class not found"})
    def get_queryset(self):
        self.validate()
        class_obj = Class.objects.get(pk=self.request.GET["class"])
        queryset = Video.objects.filter(study_class=class_obj).order_by("-date")
        return queryset

注释

  1. 使用drf ValidationError() 异常提出错误
  2. 使用django querySet的 exists() 方法检查是否有任何对象。
  3. 永远不要使用 len() 函数以检查django querySet的 count> count((非常糟糕的练习。

最新更新