22👍
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:
self.kwargs['id']
Ref: http://www.django-rest-framework.org/api-guide/filtering#filtering-against-the-url
1👍
I think you can update your view for multiple operations such as
class RetrieveUpdateAPIView(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
generics.SingleObjectAPIView):
"""
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.
0👍
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
- Changing password in Django Admin
- Where do I register an rq-scheduler job in a Django app?
- ForeignKey to a model that is defined after/below the current model
Source:stackexchange.com