0

我正在使用 django rest 框架进行项目,在该框架中我必须过滤用户给出的不同参数。我正在使用 django 过滤器后端。这是我的代码:

class FilterViewSet(viewsets.ModelViewSet):

serializer_class = SearchSerializer

#Filters on specific fields
filter_backends = (DjangoFilterBackend,)

filter_fields = ('property_zipcode','property_state', 
                 'property_county',
                 'property_city','property_area',)#range between 100 to 500 or area less then 500.

#range is pass by user as a property_area=300.

def filter_queryset(self, queryset):
    if self.request.query_params.get('property_state', None):
        queryset = super(FilterViewSet, self).filter_queryset(self.get_queryset())
        return queryset
    else:
        queryset = self.get_queryset()
        return queryset

一切正常。但现在我必须根据 100 平方英尺到 500 平方英尺的范围过滤 property_area。我如何使用 djangoFilter 后端来实现这一点?

4

1 回答 1

0

谢谢@Gabriel Muj。从 django-filter 文档中我解决了我的问题。我创建了自己的过滤器类,添加了用于过滤器的字段。

class Filter(django_filters.FilterSet):

    class Meta:
        model = Property
        fields = {
            'property_state': ['exact'],
            'year_built': ['lt', 'gt'],
            'tax':['lt','gt'],

        }

在 Viewset 中调用它:

    class FilterViewSet(viewsets.ModelViewSet):

          serializer_class = SearchSerializer

         #Filters on specific fields
          filter_class = Filter



        def filter_queryset(self, queryset):
             if self.request.query_params.get('property_state', None):
              queryset = super(FilterViewSet, self).filter_queryset(self.get_queryset())
              return queryset
          else:
              queryset = self.get_queryset()
              return queryset
于 2017-12-04T12:34:50.140 回答