覆盖.get_queryset()时如何正确返回错误?

时间:2019-02-13 09:52:42

标签: django-rest-framework django-rest-viewsets

我阅读了DRF文档,您可以通过覆盖.get_queryset()来再次过滤查询参数。我正在寻找最佳实践,以防万一过滤器不正确以及在何处返回错误消息,该如何返回。

我所指的文档是here 而且我在下面

包含了源代码
class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
        """
        Optionally restricts the returned purchases to a given user,
        by filtering against a `username` query parameter in the URL.
        """
        queryset = Purchase.objects.all()
        username = self.request.query_params.get('username', None)
        if username is not None:
            queryset = queryset.filter(purchaser__username=username)
        return queryset

谢谢您的帮助

2 个答案:

答案 0 :(得分:0)

您可以做到

from rest_framework import status

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer
    def get_queryset(self):
        try:
            """
            Optionally restricts the returned purchases to a given user,
            by filtering against a username query parameter in the URL.
            """
            queryset = Purchase.objects.all()
            username = self.request.query_params.get('username', None)
            if username is not None:
                    queryset = queryset.filter(purchaser__username=username)
            return queryset
        except:
            return None

    def get(self, request):
        try:
           data=view_serializer(self.get_queryset(),many=True).data
           context = {
               "data" : data,
               "message" : "Contents returned successfully",
               "success" : True
               }
           return Response(context, status=status.HTTP_200_OK)
        except Exception as error:
           context = {'error': str(error), 'success': "false", 'message': 'Failed To Get contents.'}
           return Response(context, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

答案 1 :(得分:0)

如果您的API严格,并且您需要发送有关错误过滤器的消息,则可能会引发错误,因此DRF知道如何处理它(docs) 例如:

from rest_framework.exceptions import ValidationError

class PurchaseList(generics.ListAPIView):
    serializer_class = PurchaseSerializer

    def get_queryset(self):
      ...
      if error:
        raise ValidationError(detail='Invalid Params')