4

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
1
  • 1
    If you're using django-filters, you should use it instead of adding more conditions in get_queryset()... Commented Jun 17, 2021 at 7:01

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.