Skip to main content

FilterBackend which takes mapping of query params to field name.

Project description

FilterMapBackend

Test Status

Table Of Content

Introduction

FilterBackend which takes mapping of query params to field name.

It takes the query_param to filter map and enables filter option in list view.

Installation

Install drf-filtermapbackend using

pip install drf-filtermapbackend

Then include filter_map in your installed apps

INSTALLED_APPS = [
    ...,
    'rest_framework',
    'filter_map',
    ...
]

Usage

You can use FilterMapBackend by adding it to your filter backends and setting filter_map attribute. For example

from rest_framework.viewsets import ModelViewSet
from filter_map.backends import FilterMapBackend

class ProfileViewSet(ModelViewSet):
    """
    Consider Profile Model has user FK,
    """
    queryset = ...
    serializer_class = ...
    filter_backends = (FilterMapBackend,)
    filter_map = {
        # plain map
        'first_name': 'user__first_name',
        
        # used with lte operator
        'joined_before': 'date_joined__date__lte',
        
        # also supports separate field name and operator 
        'last_name': ('user__last_name', 'iexact'),
    }
    

You can also define get_filter_map method to return the filter map. This will allow you to change filter_map in runtime. Here's an example

from rest_framework.viewsets import ModelViewSet
from filter_map.backends import FilterMapBackend

class ProfileViewSet(ModelViewSet):
    """
    Consider Profile Model has user FK,
    """
    queryset = ...
    serializer_class = ...
    filter_backends = (FilterMapBackend,)
    
    def get_filter_map(self):
        # Disable joined_before filter for non staff users
        if self.request.user.is_authenticated and self.request.user.is_staff:
            return {
                'first_name': 'user__first_name',
                'joined_before': 'date_joined__date__lte',
                'last_name': ('user__last_name', 'iexact'),
            }
        else:
            return {
                'first_name': 'user__first_name',
                'last_name': ('user__last_name', 'iexact'),
            }
            

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

drf-filtermapbackend-0.0.1.tar.gz (17.7 kB view hashes)

Uploaded Source

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page