Django Rest Framework List API View 的筛选后端

huangapple go评论60阅读模式
英文:

Filter Backends Django Rest Framework List API View

问题

抱歉,我只回答不包含代码的请求。以下是您要翻译的内容:

Excuse me devs, I want to ask about Django generics List API View filter_backends, how can i return none / data not found when the param is wrong or empty?

# My Django Views
class FilterTablePVPlantByPVOwnerId(filters.FilterSet):
    id = filters.CharFilter(
        field_name='id', lookup_expr='exact')

    class Meta:
        model = TablePVPlant
        fields = ['id']

class PlantListByClientView(generics.ListAPIView):
    queryset = TablePVPlant.objects.all()
    serializer_class = PlantListSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = FilterTablePVPlantByPVOwnerId

    def list(self, request, *args, **kwargs):
        if self.request.query_params:    
            response = super().list(request, *args, **kwargs)
            response.data = {'status': 'success',
                         'data': response.data, 'msg': 'done'}
        return response
英文:

Excuse me devs, I want to ask about Django generics List API View filter_backends, how can i return none / data not found when the param is wrong or empty?

# My Django Views
class FilterTablePVPlantByPVOwnerId(filters.FilterSet):
    id = filters.CharFilter(
        field_name='id', lookup_expr='exact')

    class Meta:
        model = TablePVPlant
        fields = ['id']

class PlantListByClientView(generics.ListAPIView):
    queryset = TablePVPlant.objects.all()
    serializer_class = PlantListSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = FilterTablePVPlantByPVOwnerId

    def list(self, request, *args, **kwargs):
        if self.request.query_params:    
            response = super().list(request, *args, **kwargs)
            response.data = {'status': 'success',
                         'data': response.data, 'msg': 'done'}
        return response

答案1

得分: 1

在Django和Django Rest Framework中,这些类型的问题通过引发异常来处理:

from rest_framework.exceptions import APIException


class BadParameter(APIException):
    status_code = 400
    default_detail = '参数x错误或为空'
    default_code = 'bad_param'

# ...

class PlantListByClientView(generics.ListAPIView):
    # ...
    def list(self, request, *args, **kwargs):
        # ...
        if bad_param:
            raise BadParameter()

框架的某些部分会为您引发异常,例如,在验证失败时,会引发ValidationError

英文:

In both Django and in Django Rest Framework these type of things are dealt with by raising Exceptions:

from rest_framework.exceptions import APIException


class BadParameter(APIException):
    status_code = 400
    default_detail = 'The parameter x is wrong or empty'
    default_code = 'bad_param'

# ...

class PlantListByClientView(generics.ListAPIView):
    # ...
    def list(self, request, *args, **kwargs):
        # ...
        if bad_param:
            raise BadParameter()

Some parts of the framework will raise exceptions for you, like, for example, serializes rising ValidationError when validation fails.

huangapple
  • 本文由 发表于 2023年2月19日 12:02:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75497914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定