Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django pass CommaSeparated values to GET paramater

We know that django has CommaSeperated model field. But how can we pass commaSeparated string to Django GET parameter.

Whenever i try to pass something like below as GET parameter:

1,2,3,4

I receive using below code in django view

request.GET.get('productids','')

It ends up like below in django view.

'1,2,3,4' 

Its ends up adding quotes around the array.

Please any Django experts help me with this issue.

like image 251
Vaibhav Chiruguri Avatar asked Nov 01 '25 19:11

Vaibhav Chiruguri


2 Answers

You can use getlist

param_list = request.GET.getlist('productids')

If you're passing it as a single parameter then you can construct it

param_list = [int(x) for x in request.GET.get('productids', '').split(',')]
like image 178
Sayse Avatar answered Nov 03 '25 11:11

Sayse


Django converts GET and POST params to string (or unicode). That means, if you're sending a list (array) as a GET param, you'll end up getting a string at the backend.

However, you can convert the string back to array. Maybe like this:

product_ids = request.GET.get('productids', '')
ids_array = list(product_ids.replace(',', '')) # remove comma, and make list

The ids_array would look like this - ['1', '2', '3'].

Update:

One thing worth noting is the ids in ids_array are strings, not integers (thanks to Alasdair who pointed this out in the comments below). If you need integers, see the answer by Sayse.

like image 29
xyres Avatar answered Nov 03 '25 11:11

xyres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!