I have a model like this :
class AccountViewSet(viewsets.ModelViewSet):
"""
A simple ViewSet for viewing and editing accounts.
"""
queryset = Account.objects.all()
serializer_class = AccountSerializer
permission_classes = [IsAccountAdminOrReadOnly]
How do I override the get method so when I hit /api/accounts/8 I can add some code before returning the 8th account ?
>Solution :
ModelViewSet have mixins.RetrieveModelMixin, which call when you hit /api/accounts/8.You can override retrieve method from it and do extra work.
class AccountViewSet(viewsets.ModelViewSet):
"""
A simple ViewSet for viewing and editing accounts.
"""
queryset = Account.objects.all()
serializer_class = AccountSerializer
permission_classes = [IsAccountAdminOrReadOnly]
def retrieve(self, request, *args, **kwargs):
#todo anything
instance = self.get_object()
serializer = self.get_serializer(instance)
return Response(serializer.data)