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'])
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With