Django REST框架:如何使用get_queryset()响应有用的错误消息 [英] Django REST framework: how to respond with useful error messages with get_queryset()

查看:73
本文介绍了Django REST框架:如何使用get_queryset()响应有用的错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django模型,我想通过Django Rest框架进行显示.我正在通过 get_queryset()显示模型中的所有对象.但是,我还有几个 query_params 可以过滤掉某些对象.这是我的正常工作的主要代码:

I have a django model which I want to display via Django Rest framework. I am getting all objects in the model to be displayed via the get_queryset(). However, I also have a couple of query_params which will filter out certain objects. This is my main code which is working fine:

class PlanView(generics.ListAPIView):
    """
    API endpoint which allows prices to be viewed or edited
    """

    serializer_class = PlanSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,)

    # override method
    def get_queryset(self):
        //get all objects in Plan model
        queryset = Plan.objects.all()

        // possible query parameters to be read from url
        size = self.request.query_params.get("size", None)
        price = self.request.query_params.get("price", None)

        if size is not None:
            if size == "large":
                queryset = queryset.filter(Large=True)
            elif size == "small":
                queryset = queryset.filter(Large=False)

        if price is not None:
            queryset = queryset.filter(price=price)

        return queryset

使用此 urlpattern :

path(r'API/plans', views.PlanView.as_view(), name='prices'),

唯一的问题是,当我有意在浏览器中编写以下URL时,

The only problem is that when I purposefully write the below URL in a browser,

http://127.0.0.1:8000/API/plans?size=sm

它的 query_param 值错误/拼写错误,get_query()代码将忽略它并显示对象,就好像没有过滤器一样.

which has a bad/misspelled query_param value, the get_query() code will just ignore it and display the objects as if there are no filters.

我试图输入else语句,例如:

I tried to put an else statement such as:

    if size is not None:
            if size == "large":
                queryset = queryset.filter(Large=True)
            elif size == "small":
                queryset = queryset.filter(Large=False)
            else:
                return Response({"Error":"bad request"}, status=status.HTTP_400_BAD_REQUEST)

但是,我收到一条错误消息:

but with this, I get an error message saying:

ContentNotRenderedError at /API/plans
The response content must be rendered before it can be iterated over.

如果用户在API中输入了错误的参数值,如何显示有用的错误响应/json?

How can I display useful error responses/jsons if a user puts in a wrong parameter value in the API?

推荐答案

您可以使用 ValidationError

from rest_framework.exceptions import ValidationError
# ...
        raise ValidationError(detail="size must be either 'large' or 'small'")

DRF捕获这些异常并整齐地显示它们.它返回形式为

DRF catches these exceptions and displays them neatly. It returns a JSON of the form

{
    "detail": "size must be either 'large' or 'small'"
}

这篇关于Django REST框架:如何使用get_queryset()响应有用的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆