本文由Scarb发表于金甲虫的博客,转载请注明出处

Django REST framework 支持多个id的过滤器

需求

希望在api中可以筛选多个ID,返回多个对象。

1
http://api.example.com/api/users/?ids=1,2,3,5,7

解决方法

使用django-filter
编写自定义的过滤器进行多个id对象的选择

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class IntegerListFilter(django_filters.Filter):
def filter(self,qs,value):
if value not in (None,''):
integers = [int(v) for v in value.split(',')]
return qs.filter(**{'%s__%s'%(self.name, self.lookup_type):integers})
return qs

class MyFilter(django_filters.FilterSet):
ids = IntegerListFilter(name='id',lookup_type='in')
class Meta:
model = MyModel
fields = ('ids',)

class MyModelViewSet(viewsets.ModelViewSet):
queryset = MyModel.objects.all()
serializer_class = MyModelSerializer
filter_class = MyFilter

参考资料

  1. Possible to do an in lookup_type through the django-filter URL parser?
  2. Django-filter multiple URL parameters