1

I am thinking of refactoring my code because I think I'm repeating too much ending up with lines of code. Take of this instance below I have implemented a class based view to GET,PUT,and DELETE for the Unit Model. Later I will create another view for Department to do CRUD and will follow the same pattern,is there a way I can make custom generic model views that can be dynamically used in any other view.

class UnitDetailView(generics.RetrieveAPIView):
    """ Class based view for Unit Details. """

    serializer_class = UnitSerializer
    queryset = Unit.objects.all()

    def get_object(self, pk, org_id=None):
        try:
            return Unit.objects.get(pk=pk, org_id=org_id)
        except Unit.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
        """Get a unit instance."""
        unit_obj = self.get_object(pk, org_id=get_auth(request))
        serializer = UnitSerializer(unit_obj)
        return Response(serializer.data)

    def put(self, request, pk, format=None):
        """Update a unit instance."""
        unit_obj = self.get_object(pk, org_id=get_auth(request))
        serializer = UnitSerializer(unit_obj, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        """Remove a unit instance."""
        unit_obj = self.get_object(pk, org_id=get_auth(request))
        unit_obj.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

1 Answer 1

1

You can use viewsets.ModelViewSet. And you won't need to write every method (get, put, delete, update)

Sign up to request clarification or add additional context in comments.

5 Comments

I had to override the methods to add org_id the function get_auth() returns the organization id the authenticated user is logged in. Therefore using viewsets would also require me to customize the methods like above so that I add org_id = get_auth(request)
@pmutua - where does get_auth() come from?
That is a custom function I implemented.
@pmutua - then provide its code. It's hard to say, if default behavior can help, when there is no full code
I understand, the approach I have implemented is to customize djangorestframework's mixins to fit my needs and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.