我可以使用django-filters验证filter参数吗?如果params或filter-params错误,我可以使用一些exeption吗?

mm5n2pyu  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(130)

我将一些继承逻辑封装到for drf视图中。如果我使用了错误的field-param或错误的fild-filter(例如,param和filter是:?title__contains=title,在前端我们犯了一些错误),我只是从self.filter_queryset中获取Model.objects.all()查询,没有任何异常,但我认为django-filter会验证filter_queryset方法中的参数。我将非常感谢我需要寻找的方向的提示。
听说我正在使用Django-filters:

class SomeView(GenericAPIView):
    filter_backends = [DjangoFilterBackend]
    some = SomeDTO()
    
    def some_get(self, request: Request, serializer: serializers):
        model = serializer.Meta.model
        params = request.query_params
        if params:
            query = self.filter_queryset(model.objects.all()) # problem is hear!
        else:
            query = model.objects.all()
        self.some.collect(serializer(query, many=True).data, status.HTTP_200_OK)
        return self.uni

Drf-views看起来像:

class CurrentView(SomeView):
    filterset_class = CustomerFilter

    def get(self, request: Request):
        some: SomeDTO = self.some_get(request, CurrentSerializerDepth)
        return Response(some.data, some.status)

    def post(self, request: Request):
        some: SomeDTO = self.some_create_or_update(request, CurrentSerializerFlat)
        return Response(some.data, some.status)
3pmvbmvn

3pmvbmvn1#

我实现了一个自定义的FilterSet类,当给出一个无效的查询参数时,它会抛出一个错误:

from django_filters.rest_framework import FilterSet
from rest_framework.exceptions import ParseError

class AcceptOnlyDeclaredParametersFilterSet(FilterSet):
    """FilterSet that throws an error when an invalid parameter (filter-field) is given."""

    def check_allowed_parameters(self):
        """Check if the given parameters are allowed. Raises a ParseError if they are not."""
        non_allowed = [param for param in self.data.keys() if param not in self.declared_filters.keys()]
        if non_allowed:
            raise ParseError(f"Unknown filter parameters: {non_allowed}")

    def is_valid(self):
        """Check if the filter contains valid parameters."""
        self.check_allowed_parameters()
        return super().is_valid()

相关问题