Reputation: 45
I'm trying to filter multiple query parameters with a same key, for example:
api/?city=Kazan&city=Moscow
But I get all objects which city=Kazan
I tried this code, but nothing has changed:
class FinalListView(generics.ListAPIView):
serializer_class = FinalSerializer
filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
def get_queryset(self):
condition = Q()
queryset = Final.objects.all()
city = self.request.query_params.getlist('city')
if city:
if city != 'all':
for a in city:
condition |= Q(city__startswith=a)
queryset = queryset.filter(condition)
return queryset
Upvotes: 4
Views: 2019
Reputation: 935
You have to fix indentations,
def get_queryset(self):
condition = Q()
queryset = Final.objects.all()
city = self.request.query_params.getlist('city')
if city:
if city != 'all':
for a in city:
condition |= Q(city__startswith=a)
queryset = queryset.filter(condition)
return queryset
Upvotes: 0
Reputation: 476493
You should only filter at the end of the for loop:
def get_queryset(self):
condition = Q()
queryset = Final.objects.all()
city = self.request.query_params.getlist('city')
if city:
if city != 'all':
for a in city:
condition |= Q(city__startswith=a)
# ↓ end of the for loop
queryset = queryset.filter(condition)
return queryset
Upvotes: 3