Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query params to array

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'])
like image 677
indavinci Avatar asked Feb 01 '20 01:02

indavinci


2 Answers

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)
like image 24
Ishant Dahiya Avatar answered Sep 19 '22 23:09

Ishant Dahiya


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

like image 190
Thiago Schettini Avatar answered Sep 17 '22 23:09

Thiago Schettini