Search code examples
djangodjango-viewsdjango-generic-views

Django/Python: How to write Create, List, Update and Delete in a single View or a generic view?


I am trying to write a view in which a post can be created and in the same page, the object_list will be displayed. And even an object can be updated and deleted.

Country Capital
India   Delhi       UPDATE DELETE
USA     Washington  UPDATE DELETE
-----   ------

I would appreciate helping me in achieve this or suggesting a similar type of question.


Solution

  • What you're looking for are Mixins.

    Try creating a detail view class with the following parameters:

    mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView

    For example:

    class ObjectDetail(mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.GenericAPIView):
    
        queryset = Object.objects.all()
    

    As has proposed by Daniel, if you like DRF, ViewSets are also a decent alternative. However, they're not exactly succinct so I generally avoid them when possible.

    Something like a ModelViewSet, however, is extremely clear-cut and the approach I generally choose.

    Here's an example:

    class ObjectViewSet(viewsets.ModelViewSet):
    
        queryset = Object.objects.all()
    
        def perform_create(self, serializer):
            serializer.save(owner=self.request.user)
    

    Beautiful, isn't it?

    For more details, see the DRF tutorial: http://www.django-rest-framework.org/tutorial/6-viewsets-and-routers/