简体   繁体   English

使用Django Rest Framework按多个django-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. 如果所有提供的字词都匹配,则默认SearchFilter仅允许我们过滤(在我的情况下为标签)。

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. 使用上述URL,只有在对象上存在所有标签的情况下,我才可以获取对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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