indavinci
indavinci

Reputation: 165

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'])

Upvotes: 12

Views: 16520

Answers (3)

Ishant Dahiya
Ishant Dahiya

Reputation: 111

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)

Upvotes: 6

Zhigal
Zhigal

Reputation: 61

If you have function based view this should work:

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

Upvotes: 6

Thiago Schettini
Thiago Schettini

Reputation: 678

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

Upvotes: 28

Related Questions