I am building a Django application that exposes a REST API by which users can query my application's models. I'm following the instructions here
My Route looks like this in mySites url.py:
router.register(r'myObjects', views.MyObjectsViewSet)
....
url(r'^api/', include(router.urls)),
My Serializer looks like this:
class MyObjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = MyObject
fields = ('id', 'name',)
My Viewset looks like this:
class MyObjectsViewSet(viewsets.ModelViewSet):
queryset = MyObjects.objects.all()
serializer_class = MyObjectSerializer
When I hit the API /api/myObjects/ it gives me a listing of all the myObject models. When I hit the API /api/myObjects/60/ it gives me only the myObject with id == 60. Great so far!
However, I want to change the logic of MyObjectsViewSet() such that I can manipulate/change what it returns when I hit /api/myObjects/60/. So instead of doing MyObjects.objects.all() I want to do something more complex based on the myObject ID of 60. But how can I do that?? In this viewset, how can I grab that number 60? It is not passed in as an argument. But I really need it!
I think you can update your view for multiple operations such as
Please watch this tutorial it will help you to understand the REST framework.
In your router, register one more url with:
and in your viewset you can grab the id with:
Ref: http://www.django-rest-framework.org/api-guide/filtering#filtering-against-the-url