How to use normal Filter together with SearchFilter on Django Rest Framework?

后端 未结 2 1350
名媛妹妹
名媛妹妹 2021-02-13 04:48

I\'m using DRF(Django Rest Framework).

I declared a ModelViewSet, and now I want to add filters on that.

class GoodsViewSet(viewsets.ModelViewSet):
    c         


        
相关标签:
2条回答
  • 2021-02-13 05:24

    this worked for me:

        from django_filters import rest_framework as filters
        from django_filters.rest_framework import DjangoFilterBackend
        from rest_framework.filters import SearchFilter, OrderingFilter
    

    --------views.py-----------------------------

        filter_backends = (filters.DjangoFilterBackend, SearchFilter ,OrderingFilter)
        filter_fields =('completed',)
        ordering =('-date_created',)
        search_fields =('task_name',)
    
    0 讨论(0)
  • 2021-02-13 05:28

    Finally, I found we should specify two filter_backends together:

    from rest_framework.filters import SearchFilter
    from django_filters.rest_framework import DjangoFilterBackend
    
    class GoodsViewSet(viewsets.ModelViewSet):
        class Filter(FilterSet):    
            class Meta:
                model = m.Goods
    
        filter_class = Filter
        filter_backends = (SearchFilter, DjangoFilterBackend)
        search_fields = ['name',]
        queryset = m.Goods.objects.all()
        serializer_class = s.GoodsSerializer
    

    Or we can ignore the filter_backends field on a specific ViewSet class, but apply them globally in settings.py:

    REST_FRAMEWORK = {
        # ... other configurations
        'DEFAULT_FILTER_BACKENDS': (
            'rest_framework.filters.SearchFilter',
            'django_filters.rest_framework.DjangoFilterBackend',
        ),
    }
    

    So that the filter_class and search_fields options are available on the ViewSet at the same time.

    0 讨论(0)
提交回复
热议问题