Sylph
Sylph

Reputation: 151

Django: filter queryset by multiple ID

My query is quite simple, I have a model Vendor in my Django REST app. What I want is to use a get response with a few ID and get back all the respective models with these ID. The GET url pattern could be something like this: r'^api/vendors?id=1,2,3'.

What I'm thinking of right now is to use ListAPIView, and in the list method filter my queryset with all the id in the url. But I'm not sure exactly how to achieve this (filtering queryset with a list of id, I'm very new to both Python and Django), so if anyone can provide any advice on this it would be greatly appreciated.

Upvotes: 5

Views: 8794

Answers (1)

Stefan Collier
Stefan Collier

Reputation: 4682

(Unfortunately I do not know django REST, so here is a pure django solution)

Using the ListAPIView you can access the URL (or GET) params and modify the queryset.

class MyVendorView(ListAPIView):
    # attributes

    def get_queryset(self):
        id_string = self.request.GET.get('id')
        if id_string is not None:
            ids = [int(id) for id in id_string.split(',')]
            return Vendor.objects.filter(id__in=ids)

        else:
            return Vendor.objects.all()

    # other methods

please note that I'm ingoring any attributes or other attributes needed

What's happening here then?

  • Overriding get_queryset will control what results we get from hitting the view

  • self.request.GET.get('id') Will extract the value of the id query parameter from the url like so localhost:8000/api/vendors?id=1,2,3 the result will be a string "1,2,3".

  • filter(id__in=ids) lets you say select stuff that has an value in this list of ids

Upvotes: 13

Related Questions