AverageJoe
AverageJoe

Reputation: 63

end point to accept multiple values, including query strings

I have a view which should accept an end point with a query parameter, as well as without a parameter.

http://localhost:8001/v1/subjects?owner_ids=62,144

and

http://localhost:8001/v1/subjects

Here's my view file...

class SubjectPagination(JsonApiPageNumberPagination):
    """
    Required for frontend to retrieve full list.
    """
    max_page_size = 5000


class SubjectViewSet(Subject.get_viewset()):
    pagination_class = SubjectPagination

    def get_queryset(self):
        import pdb; pdb.set_trace()
        queryset = Subject.objects.all()

        if self.request.GET['owner_ids']:
            owner_id_list = self.request.GET['owner_ids'].split(',')
            owner_id_list_integer = []

            for i in owner_id_list:
                owner_id_list_integer.append(int(i))

            return queryset.filter(organization__in=owner_id_list_integer)

        else:

            return queryset


SubjectUserRoleViewSet = Subject.get_by_user_role_viewset(
    SubjectViewSet, GroupRoleMap, Role)

I am trying to figure out how to handle both the end points? Please advice what needs to be done at the view to handle a URI with or without query strings?

Here's the urls.py

router.register(r'subjects', views.SubjectViewSet)

Upvotes: 0

Views: 53

Answers (1)

beren5000
beren5000

Reputation: 100

First of all, is a good practice to send the parameters in url-form-encode, avoiding things like that, in this case for send a list you could send id as:

?owner_ids[]=62&owner_ids[]=144

the querydict its going to be like this :

<QueryDict: {'owner_ids[]': ['62', '144']}>

and you could process it easily, like this

self.request.GET.getlist('owner_ids[]', [])

remember to use the get and get list functions of the request method GET and POST, to avoid dict errors.

Second, split returns a list the for statement in owner list id is totally unnecessary, and the queryset statement __in accept array of strings, if you actually want to convert all the items to integers use list comprehensions. For example, to convert all the items in a list to integer, just have to use:

owner_ids = [int(i) for i in owner_ids ]

this is way more fast in python and way more pythonic, and also cool too see.

and last, all urls should finish in /, even django has a settings for that called append_slash

this is what i can tell about the ambiguous question you are asking, in the next times please write questions more precisely that help people help you.

Upvotes: 1

Related Questions