Django-Filter and query with an array
The answer given by doniyor is quite apt. But I guess request
won't be available where it is used.
There is another way of doing this.You can override the get_queryset
method. This can be done as follows:
class BoatList(generics.ListCreateAPIView):
permission_classes = (IsOwnerOrReadOnly,)
serializer_class = BoatSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('id', 'home_port',)
def get_queryset(self):
id_list = self.request.GET.getlist("id")
if not id_list:
return []
return Boat.objects.filter(id__in=id_list)
try this:
url: http://127.0.0.1:8000/api/v1/boats/boats?id=10,11
class BoatList(generics.ListCreateAPIView):
permission_classes = (IsOwnerOrReadOnly,)
serializer_class = BoatSerializer
queryset = Boat.objects.filter(id__in=request.GET.getlist('id')) #<------
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('id', 'home_port',)
you just creat a filter class
class NumberInFilter(BaseInFilter, NumberFilter):
pass
class myFilter(FilterSet):
id__in = NumberInFilter(field_name='id', lookup_expr='in')
class Meta:
model = Boat
in the viewset use the
filter_class = myFilter
you can see this document of the django-filter: https://django-filter.readthedocs.io/en/master/ref/filters.html?highlight=BaseInFilter