0

I have EmberJS front-end which calls Django REST API. I am passing string array from front-end to the API as shown below:

Back-end Request http://localhost:8000/api/v1/User/search/?active=true&city%5B%5D=newyork&city%5B%5D=chicago&city%5B%5D=boston

HTML Decoded http://localhost:8000/api/v1/User/search/?active=true&city[]=newyork&city[]=chicago&city[]=boston

Some how I am not able to get rid of the extra %5B%5D (which is square brackets) from this request as EmberJS automatically adds that as the parameter is passed as string array. I searched over several forums but did not get a solution for it.

How to read the string array (City parameter) in Django API and get all passed values from EmberJS front-end?

Rohan
  • 11
  • 5

1 Answers1

1

You do not need to get rid of the []. The are good practice to indicate "I really do want to pass an array, i.e. multiple values for this query parameter".

The [] are presumably there because ember-data in your front end uses coalesceFindRequests. Dustin Farras (the main author of the ember-Django-adapter) has written an article about using his adapter with coalesceFindRequests: You can define a filter that covers [] and simply tell the django-rest-framework to use it:

# myapp/filters.py
from rest_framework import filters

class CoalesceFilterBackend(filters.BaseFilterBackend):
"""
Support Ember Data coalesceFindRequests.
"""
def filter_queryset(self, request, queryset, view):
    id_list = request.query_params.getlist('ids[]')
    if id_list:
        # Disable pagination, so all records can load.
        view.pagination_class = None
        queryset = queryset.filter(id__in=id_list) # adapt here, see note below
    return queryset 

Now you just need to add this filter to filter_backends in your views, e.g.:

from myapp.filters import CoalesceFilterBackend

class UserListView(generics.ListAPIView):
    queryset = User.objects.all()
    serializer = UserSerializer
    filter_backends = (CoalesceFilterBackend,)

Or, configure it globally in your DRF settings:

REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('myapp.filters.CoalesceFilterBackend',) }

Note: You will need to adapt the filter for cities, of course. (When filtering for primary keys, I prefer to filter for pk__in= instead of id__in= that also covers primary keys with names other than id.)

arne.b
  • 4,212
  • 2
  • 25
  • 44