Search code examples
pythondjangotagsdjango-rest-frameworkdjango-taggit

Filter by multiple django-taggit tags with Django Rest Framework


Default SearchFilter only allows us to filter (tags in my case) if all the provided terms are matched.

class MyModelViewSet(viewsets.ReadOnlyModelViewSet):
    filter_backends = (filters.SearchFilter, )
    search_fields = ('tags__name',)
    serializer_class = MyModelSerializer
    model = MyModel
    queryset = MyModel.objects.all()

Filtering then works with:

http://localhost:8000/api/v1/objects/?search=tag1,tag2

With above URL I only get objects if all tags are present on the object.

Is there any chance I could make this filter to allow me to filter if any of the provided tags match?


Solution

  • I have managed to do it with custom filter backend:

    class TagsFilter(filters.BaseFilterBackend):
        """
        Return all objects which match any of the provided tags
        """
    
        def filter_queryset(self, request, queryset, view):
            tags = request.query_params.get('tags', None)
            if tags:
                tags = tags.split(',')
                queryset = queryset.filter(tags__name__in=tags).distinct()
    
            return queryset