过滤器后端Django Rest框架列表API视图

dwbf0jvd  于 2023-02-25  发布在  Go
关注(0)|答案(1)|浏览(130)

打扰一下devs,我想问一下Django泛型List API View filter_backends,当参数错误或为空时,我如何返回none / data not found?

# 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
pxy2qtax

pxy2qtax1#

在Django和Django Rest Framework中,这类事情都是通过提升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()

框架的某些部分会为您引发异常,例如,当验证失败时,序列化上升的ValidationError

相关问题