[Fixed]-How can I grab the API parameter in a Django viewset?


In your router, register one more url with:

router.register(r'myObjects/(?P<id>\d+)', views.MyObjectsViewSet)

and in your viewset you can grab the id with:


Ref: http://www.django-rest-framework.org/api-guide/filtering#filtering-against-the-url


I think you can update your view for multiple operations such as

class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
Concrete view for retrieving or updating a model instance.
FIXME: the newest version of rest_framework has this class

def get(self, request, *args, **kwargs):
    return self.retrieve(request, *args, **kwargs)

def put(self, request, *args, **kwargs):
    return self.update(request, *args, **kwargs)

def create(self, request, *args, **kwargs):
    return self.create(request, *args, **kwargs)

Please watch this tutorial it will help you to understand the REST framework.


I feel cyriacthomas is right but might need a bit more details. Although I am just unsure as to why the self is used.

I believe the snippet would look like:

class MyObjectsViewSet(viewsets.ModelViewSet):
    queryset = MyObjects.objects.all()
    serializer_class = MyObjectSerializer

    # Inside your class, you overwrite the retrieve function
    def retrieve(self, request, *args, **kwargs):
        obj_id = kwargs['id']

        query = MyObjects.objects.get(obj_id)

        # do something with data

        return self.serializer_class(data=query).data

Leave a comment