Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-rest-framework : list parameters in URL

I am pretty new to django and django-rest-framework, but I am trying to pass lists into url parameters to then filter my models by them.

Lets say the client application is sending a request that looks something like this...

  url: "api.com/?something=string,string2,string3&?subthings=sub,sub2,sub3&?year=2014,2015,2016/"

I want to pass in those parameters "things", "subthings", and "years" with their values.

Where the url looks something like this?

NOTE: Trick is that it won't be always an array of length 3 for each parameter.

Can someone point me in the right direction for how my url regex should be handing the lists and also retrieving the query lists in my views.

Thanks!

like image 358
JT. Avatar asked Sep 01 '16 17:09

JT.


2 Answers

To show how I did this thanks to the document links above. Note: I used pipes as my url delimiter and not commas -> '|'.

in my urls.py

url(r'^$', SomethingAPIView.as_view(), name='something'),

in my views.py

class SomethingAPIView(ListAPIView):
  # whatever serializer class

  def get_queryset(self):
    query_params = self.request.query_params
    somethings = query_params.get('something', None)
    subthings = query_params.get('subthing', None)
    years = query_params.get('year', None)

    # create an empty list for parameters to be filters by 
    somethingParams = []
    subthingsParams = []
    yearParams = []

    # create the list based on the query parameters
    if somethings is not None:
      for something in somethings.split('|'):
        countryParams.append(int(something))
    if subthings is not None:
      for subthing in subthings.split('|'):
        subthingsParams.append(int(subthing))
    if years is not None:
      for year in years.split('|'):
        yearParams.append(int(year))

    if somethings and subthings and years is not None:
      queryset_list = Model.objects.all()
      queryset_list = queryset_list.filter(something_id__in=countryParams)
      queryset_list = queryset_list.filter(subthing_id__in=subthingsParams)
      queryset_list = queryset_list.filter(year__in=yearParams)
      return queryset_list

I do need to check for an empty result if they are not valid. But here is starting point for people looking to pass in multiple values in query parameters.

A valid url here would be /?something=1|2|3&subthing=4|5|6&year=2015|2016.

like image 115
JT. Avatar answered Oct 10 '22 10:10

JT.


Checkout this doc http://www.django-rest-framework.org/api-guide/filtering/

Query params are normally not validated by url regex

like image 32
glmvrml Avatar answered Oct 10 '22 12:10

glmvrml