Search code examples
djangodjango-rest-frameworkdjango-rest-viewsets

Django Rest API merging delete/get/update/get methond in two class


At first you see my 4 method class in view.py:

class ContactList(ListAPIView):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializers

# This is delete method
class ContactDelete(DestroyAPIView):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializers
    lookup_field = 'pk'

#below is post method to create new contact
class ContactCreate(CreateAPIView):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializers

#below is put and patch method to update contact
class ContactUpdate(UpdateAPIView):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializers
    lookup_field = 'pk'

I want ContactList and ContactCreate should be in one class

and ContactDelete and ContactUpdate should be in one class

i am not getting how to merge it, can anyone tell me how to do it?

Note: i dont want APIViewSet


Solution

  • DRF has already to classes for that purpose. You can check them here and here

    from rest_framework.generics import ListCreateAPIView, RetrieveDestroyAPIView
    
    
    class ContactCreateListAPIView(ListCreateAPIView):
        queryset = Contact.objects.all()
        serializer_class = ContactSerializers
    
    
    class ContactRetrieveDeleteAPIView(RetrieveDestroyAPIView):
        queryset = Contact.objects.all()
        serializer_class = ContactSerializers
        lookup_field = 'pk'