起初,您在view.py:
中看到了我的4个方法类
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'
我希望ContactList
和ContactCreate
应该在一个班级里
并且ContactDelete
和ContactUpdate
应该在一个类中
我没有如何合并它,有人可以告诉我该怎么做吗?
注意:我不要APIViewSet
答案 0 :(得分:2)
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'
答案 1 :(得分:2)
希望这会有所帮助
# 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
由于DRF将 lookup_field = 'pk'
作为默认值,因此您可以从视图中删除 pk
。