五个接口最终版
#url.py
# 序列化最贱版本
url(r'^customer/$', views.CustomerView.as_view({"get":"list","post":"create"})),
url(r'^customer/(?P<pk>d+)', views.CustomerView.as_view({"get":"retrieve","put":"update","delete":"destroy"})),
views.py
from rest_framework.serializers import ModelSerializer
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model=Customer
# field=["name","gender"]
fields="__all__"
from rest_framework.viewsets import ModelViewSet
class CustomerView(ModelViewSet): #将五个数据接口全部封装在了ModelViewSet
queryset = Customer.objects.all()
serializer_class = CustomerSerializer
五个接口最终版源码解析
#url(r'^authors/(?P<pk>d+)/', views.AuthorsView.as_view({"get":"retrieve","delete":"destroy","put":"update"})),
#url(r'^authors/$', ViewSetMixin.as_view({"get":"retrieve","delete":"destroy","put":"update"})),
#url(r'^authors/$', ViewSetMixin.view),
一旦用户访问,get访问authors/1:
ViewSetMixin.view(reqeust):
for method, action in actions.items(): # {"get":"retrieve","delete":"destroy","put":"update"}
handler = getattr(self, action) # handler===self.retrieve handler=== destroy handler===update
setattr(self, method, handler) # self.get=self.retrieve self.delete=self.destroy self.put=self.update
return self.dispatch(request, *args, **kwargs)
#
APIView.dispatch(request):
handler = getattr(self, request.method.lower()) # self.retrieve
response = handler(request, *args, **kwargs)
# def retrieve(self.request):
` # return .....
return response