DjangoFilterBackend with multiple ids

2019-02-09 06:22发布

I want to filter my model with django-filter. It works fine if I filter by one id like:

http://localhost:8000/accommodations?accommodationType_id=1

But I don't know how I can filter by multiple ids like.

http://localhost:8000/accommodations?accommodationType_id=1,2

My actual ViewSet looks like this:

class AccommodationViewSet(viewsets.ReadOnlyModelViewSet):
    """
        REST API endpoint for 'accommodation' resource
    """
    queryset = Accommodation.objects.all()
    serializer_class = AccommodationSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('accommodationType_id', 'name')

I hope there is an solution.

1条回答
趁早两清
2楼-- · 2019-02-09 07:26

I found the following solution for my problem :)

https://gist.github.com/aBuder/654fb945f085b17358d8

from webapp.serializers import *
from rest_framework import viewsets
from rest_framework import filters
from django_filters import Filter, FilterSet


class ListFilter(Filter):
    def filter(self, qs, value):
        if not value:
            return qs

        # For django-filter versions < 0.13, use lookup_type instead of lookup_expr
        self.lookup_expr = 'in'
        values = value.split(',')
        return super(ListFilter, self).filter(qs, values)


class AccommodationFilter(FilterSet):
    ids = ListFilter(name='id')
    accommodationType_ids = ListFilter(name='accommodationType_id')

    class Meta:
        model = Accommodation
        fields = ['ids', 'accommodationType_ids']


class AccommodationViewSet(viewsets.ReadOnlyModelViewSet):
    """
        REST API endpoint for 'accommodation' resource
    """
    queryset = Accommodation.objects.all()
    serializer_class = AccommodationSerializer
    filter_backends = (filters.DjangoFilterBackend,)
    filter_class = AccommodationFilter
查看更多
登录 后发表回答