Mixin To Add Filters to Multiple FilterSet

249 views
Skip to first unread message

Sam Christensen

unread,
Jul 27, 2020, 4:11:36 PM7/27/20
to django-filter
I am working on an application that has a view that has multiple filters that need to be applied across multiple APIs. To simplify this, I am trying to write a mixin that declares and implements these filters generically, and then other FilterSets can just inherit from it.

Here is an example of what I am trying to do:

class FilterMixin(object):
    some_filter = NumberInFilter(method='filter_some_filter') 
   
    def filter_some_filter(self, queryset, name, value):
    """
    Some fancy logic
    """
    return queryset

class InvoiceFilter(FitlerMixin, FilterSet):
    class Meta:
        model = models.Invoice

class BillFilter(FilterMixin, FilterSet):
    class Meta:

        model = models.Bill

But the FilterSet never actually picks it up as a field, instead I have to create write it this way in order to accomplish the desired behavior.

class FilterMixin(object):   
    def filter_some_filter(self, queryset, name, value):
    """
    Some fancy logic
    """
    return queryset

class InvoiceFilter(FitlerMixin, FilterSet):
    some_filter = NumberInFilter(method='filter_some_filter') 
    class Meta:
        model = models.Invoice

class BillFilter(FilterMixin, FilterSet):
          some_filter = NumberInFilter(method='filter_some_filter') 
    class Meta:
        model = models.Bill

I realize it's a small difference, but I just want to know if anyone has any ideas on how i can do this without having to add code to each FilterSet, as that means I will probably have more bugs :) 

Thanks!

Sam Christensen

Reply all
Reply to author
Forward
0 new messages