2

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.

2 Answers2

5

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(',')]
Sayse
  • 42,633
  • 14
  • 77
  • 146
  • That would work for a query string like `?product_ids=1&product_ids=2&...`. I think the OP has something like `?product_ids=1,2,3,4` – Alasdair Mar 08 '16 at 13:29
  • @Alasdair - Ah ok, if thats the case I think I might have answered that previously... I'll try to find it. – Sayse Mar 08 '16 at 13:29
  • @Alasdair - I found it in a [comment you left previously](http://stackoverflow.com/questions/35483580/passing-a-list-through-url-in-django/35483756#comment58666329_35483756), I feel kind of wierd adding it to my own answer so if you wish to create your own answer with it I'd happily delete mine – Sayse Mar 08 '16 at 13:34
  • 1
    There's already two answers, I don't think I need to add a third ;) – Alasdair Mar 08 '16 at 13:36
  • 1
    `param_list = [int(x) for x in request.GET.get('productids', []).split(',')]` This worked like a charm – Vaibhav Chiruguri Mar 08 '16 at 13:36
  • @Alasdair - Yes of course thanks! (Still feels like a weird answer..) – Sayse Mar 08 '16 at 13:38
3

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.

Community
  • 1
  • 1
xyres
  • 20,487
  • 3
  • 56
  • 85
  • That will give a list of strings, the OP wants a list of integers. – Alasdair Mar 08 '16 at 13:28
  • @Alasdair Yes, that's right. But if OP needs to query products from DB, Django will automatically convert ids to integers. – xyres Mar 08 '16 at 13:31
  • We don't know that the op is going to use the array to query products from the db. Imagine they do `if 2 in ids_array:` -- that's going to behave differently if you haven't converted to integers. – Alasdair Mar 08 '16 at 13:32
  • @Alasdair That's a good case! I'll try and update accordingly. – xyres Mar 08 '16 at 13:34