Snippet: OR filters with Django-filter

Spread the love

The requirement is to build a simple OR condition query string filter using django-filter. Since there is no standardization of the format, I have used a query string which looks like ?value=v1|v2|v3
Here’s a simple implementation using Django’s Q objects.

class MultiValueCharFilter(filters.Filter):
    def __init__(self, *args, **kwargs):
        self.method_multivalue = kwargs.pop('method_multivalue')
        super(MultiValueCharFilter, self).__init__(*args, **kwargs)
    def filter(self, qs, value):
        q = Q()
        for v in value.split('|'):
            q = q | Q(**{self.method_multivalue: v})
        return qs.filter(q)
names = MultiValueFilter(method_multivalue='name')

You can re-use the below filter using method_multivalue

class UserFilter(filters.FilterSet):
    class Meta:
        model = User
    names = MultiValueFilter(method_multivalue='first_name')

Finally query using ?names=Tom|Dick|Harry

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *