0

Is there a pre-built deserializer for query strings like:

foo[]=1&foo[]=2&foo[]=34&....&foo[]=5

Currently I am just working the string with replace and split to get a sequence with all the values, but I am curious if there isn't some utility/helper method in Python or Django to do this.

Obviously Django is able to do very similar things when processing requests, but I a) don't know if/how I can use it and b) if it is possible to receive a sequence from the foo[] notation.

Note: I am not able to change the source string, since it originates from a third party package.

UPDATE

Thanks for your replies. My values come from POST, so I did the following (not sure if there is a more direct way, like the answers used with request.GET.getlist()):

foo = QueryDict(request.POST.get('my_var_name')).getlist('foo[]')
sthzg
  • 5,514
  • 2
  • 29
  • 50

2 Answers2

2

Firstly, there's absolutely no reason to send data with the [] prefix. That's a PHP or Rails idiom, and has no place in Django.

To get a list from a repeated parameter, though, you can just use getlist:

foos = request.GET.getlist('foo[]')
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • @MartijnPieters I believe you can disable that in jQuery by setting `jQuery.ajaxSettings.traditional = true;`. – Daniel Roseman May 29 '14 at 07:55
  • Ah, I knew I'd missed a switch somewhere. Indeed, `traditional = true` will disable the dismal default setting. – Martijn Pieters May 29 '14 at 07:57
  • I'd really like to accept both of your answers. Came in exactly the same time. Super useful information with the ```traditional``` setting in jQuery. – sthzg May 29 '14 at 08:25
2

Just retrieve all values with the getlist() method:

foo_list = request.GET.getlist('foo[]')

Include the brackets, they are just part of the name.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • +1 for linking to the QueryDict docs. Useful read up and exactly what I was hoping to find. As noted, the part generating the bracketed string lives in a third party tool that I want to leave unchanged. – sthzg May 29 '14 at 08:32