简体   繁体   English

Django REST框架过滤器后端

[英]Django REST Framework filter backend

I try to implement some basic filtering on my GenericAPIView, like this: 我尝试在我的GenericAPIView上实现一些基本过滤,如下所示:

  • view: 视图:

     class OperatorList(generics.GenericAPIView): permission_classes = (permissions.IsAuthenticated, IsAdmin) filter_class = OperatorsFilter serializer_class = OperatorSerializer def get_queryset(self): queryset = self.request.user.operators.all() def get(self, request, *args, **kwargs): serializer = OperatorSerializer(instance=self.get_queryset(), many=True, context=self.get_serializer_context()) return Response(serializer.data) 
  • serializer: 序列化器:

     class OperatorSerializer(serializers.ModelSerializer): class Meta: model = Operator fields = ['id', 'name', 'created', ] 
  • filter set: 过滤器集:

     import rest_framework_filters from rest_framework import filters from .models import Operator class OperatorFilter(filters.FilterSet): created = rest_framework_filters.DateTimeField(lookup_type='gte') class Meta: model = Operator fields = ('name', 'created', ) 

The issue is that filters are displayed in browsable API, but 'Created' is not a DateTimeWidget , but a simple input. 问题是过滤器显示在可浏览的API中,但是'Created'不是DateTimeWidget ,而是一个简单的输入。 Also, applying filter takes no effect, and I still have to catch request.query_params in get_queryset() (I ama trying to use filter backend to avoid this in first turn). 另外,应用过滤器不起作用,我仍然必须在get_queryset()捕获request.query_params (我非常想尝试使用过滤器后端来避免这种情况)。

Does anybody have any suggestions? 有人有什么建议吗?

The problem here is that you've subclassed GenericAPIView and then not (re-)implemented any of the handy logic that Django REST Framework provides in its concrete view class. 这里的问题是您已经GenericAPIView ,然后没有(重新)实现Django REST Framework在其具体视图类中提供的任何方便的逻辑

Instead you want to subclass ListAPIView which provides a get method implementing the filtering behaviour you're looking for. 相反,您想为ListAPIView子类化, ListAPIView提供了一个get方法,该方法实现了您正在寻找的过滤行为。

The magic all resides in ListModelMixin which filters the queryset as needed... 魔术全部驻留在ListModelMixin ,该模型根据需要过滤查询集...

class ListModelMixin(object):
    """
    List a queryset.
    """
    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        ... method continues ...

Your final view class should then look something like this: 然后,您的最终视图类应如下所示:

class OperatorList(generics.ListAPIView):

    permission_classes = (permissions.IsAuthenticated, IsAdmin)

    filter_class = OperatorsFilter
    serializer_class = OperatorSerializer

    def get_queryset(self):
        queryset = self.request.user.operators.all()

I hope that helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM