Using custom methods in filter with django-rest-framework

后端 未结 2 1264
耶瑟儿~
耶瑟儿~ 2021-02-19 10:45

I would like to filter against query params in my REST API - see django docs on this. However, one parameter I wish to filter by is only available via a model @property

2条回答
  •  生来不讨喜
    2021-02-19 11:37

    Use the 'action' parameter to specify a custom method - see django-filter docs

    First define a method that filters a queryset using the value of the category parameter:

        def filter_category(queryset, value):
            if not value:
                return queryset
    
            queryset = ...custom filtering on queryset using 'value'...
            return queryset
    

    Listing filter should look like this:

        class ListingFilter(django_filters.FilterSet):
            ...
            category = django_filters.CharFilter(action=filter_category)
            ...
    

提交回复
热议问题