Django Rest API将删除/获取/更新/获取方法合并为两个类

时间:2019-05-22 08:56:05

标签: django django-rest-framework django-rest-viewsets

起初,您在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'

我希望ContactListContactCreate应该在一个班级里

并且ContactDeleteContactUpdate应该在一个类中

我没有如何合并它,有人可以告诉我该怎么做吗?

注意:我不要APIViewSet

2 个答案:

答案 0 :(得分:2)

DRF已经为此目的而分类。您可以检查它们herehere

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