我想用django-filter过滤模型。如果我按一个ID进行过滤,则效果很好:
http://localhost:8000/accommodations?accommodationType_id=1
但是我不知道如何通过多个ID进行过滤。
http://localhost:8000/accommodations?accommodationType_id=1,2
我实际的
ViewSet
看起来像这样: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')
我希望有一个解决方案。
最佳答案
我为我的问题找到了以下解决方案:)
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
关于django - 具有多个ID的DjangoFilterBackend,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31029792/