Search code examples
arraysdjangoquerystringparameter

Django : array within a query string as foo[]=bar1&foo[]=bar2


I need to prepare a Django microservice that offer the following url pattern :

http://<myserver>/getinfo/?foo[]=bar1&foo[]=bar2

it seems to be a very PHP way of doing but i have to mimic it in django ...

Is there a standard way in Django for both designing the URL and retrieving the querystring parameter as a list in the View ?


Solution

  • wrt/ "designing the url", Django's urlpatterns ignore the querystring (they only match on the path), so you don't have anything to do here.

    wrt/ retrieving the querystring params as a list, that's already handled by Django's QueryDict:

    QueryDict.getlist(key, default=None)

    Returns a list of the data with the requested key. Returns an empty list if the key doesn’t exist and a default value wasn’t provided. It’s guaranteed to return a list unless the default value provided isn’t a list.

    NB: forgot to add that Django will not automagically remove the brackets from the key so you'll need foos = request.GET.getlist("foo[]") (thanks Daniel Roseman)