12

I am trying to get the results from an array as explained here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#in

http://127.0.0.1:8000/blogs?years=['2018', '2019']
http://127.0.0.1:8000/blogs?years=[2018, 2019]

Turns out ['2018', '2019'] is not what i am getting as years , even though visually they look exactly the same.

I even tried using getlist as explained here how to get multiple results using same query params django this does produce the desired results

def get_queryset(self):
        years = self.request.query_params.get('years')
        return self.queryset.filter(year__in=years)

Any clue on what am i doing wrong here?

I tried all options it does not work, while i type in the below statement it works perfectly fine

def get_queryset(self):
        return self.queryset.filter(year__in=['2018', '2019'])

3 Answers 3

28

I don't believe this way will work. When you pass the value in querystring, I guess Django will recieve as a string.

- EDIT -

The above answer wont work is need to add more years, I got the solution 127.0.0.1:8000/blogs?years=2018&years=2019 and

years = self.request.query_params.getlist('years', '')

converts this to list.

– @indavinci

Sign up to request clarification or add additional context in comments.

2 Comments

The above answer wont work is need to add more years, I got the solution 127.0.0.1:8000/blogs?years=2018&years=2019 and years = self.request.query_params.getlist('years', '') converts this to list.
Perfect! Will add your solution to the answer ;)
7

If you have function based view this should work:

request.GET.getlist('years', '')

1 Comment

years = request.GET.getlist('years', [] )
6

I think a better a better and cleaner way to solve this problem is to just pass the string as comma-separated values in query params and split them up in your Django View.

URL:

http://127.0.0.1:8000/blogs?years=2018,2019

Your View:

def get_queryset(self):
    years = self.request.query_params.get('years').split(',')
    return self.queryset.filter(year__in=years)

1 Comment

this is the way

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.