user11149657
user11149657

Reputation:

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

Upvotes: 1

Views: 704

Answers (2)

Higor Rossato
Higor Rossato

Reputation: 2046

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'

Upvotes: 1

JPG
JPG

Reputation: 88519

Hope this helps

# This is create and list method
class ContactListCreate(ListAPIView, CreateAPIView):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializers


# This is delete and update method
class ContactDeleteUpdate(DestroyAPIView, UpdateAPIView):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializers

You can remove lookup_field = 'pk' from the view, since DRF took pk as the default value.

Upvotes: 1

Related Questions