简体   繁体   中英

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?

Works for me:

from django_filters import rest_framework as filters

class TagsFilter(filters.CharFilter):
    def filter(self, qs, value):
        if value:
            tags = [tag.strip() for tag in value.split(',')]
            qs = qs.filter(tags__name__in=tags).distinct()

        return qs


class MediaPublicationFilter(filters.FilterSet):
    tags = TagsFilter(name="tags")

    class Meta:
        model = MediaPublication

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM