url前端
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^books/$', views.BookHandle.as_view()), url(r'^books/(\d+)', views.GetBookHandle.as_view()), url(r'^publishs/$', views.PublishHandel.as_view()), ]
viewspython
##################################################### # request => Request => request.data (APIView執行流程,且封裝了一些組件) from rest_framework.views import APIView from rest_framework import serializers # 序列化組件 from rest_framework.response import Response # 給前端返回消息 from app01 import models # delete,post,delete方法 用到的序列化組件 class BookSerializer(serializers.ModelSerializer): class Meta: model = models.Book fields = '__all__' # get方法 用到的序列化組件 class BookSerializer_get(serializers.ModelSerializer): class Meta: model = models.Book fields = '__all__' # 拿到Book表的全部字段['price','title'] # 除了Book表的price字段(拿到其餘全部字段),exclude不能和fields同時用 # exclude = ('price',) #針對多對一字段的序列化,裏面有source='',裏面寫關聯的字段名字.被關聯表的字段 publish = serializers.CharField(max_length=32, source='publish.name') #針對多對多字段的序列化 authors = serializers.SerializerMethodField() # 多對多字段名前面加get_ 自動執行該方法.傳入的參數就是Book表的model對象 def get_authors(self,obj): lis = [] authors_obj = obj.authors.all() for author_obj in authors_obj: dic = {} dic['name'] = author_obj.name lis.append(dic) return lis # 應用序列化組件 class BookHandle(APIView): def get(self,request): book_list_obj = models.Book.objects.all() # get方法時,自定義序列化參數是查詢的到的表的model對象,many msg = BookSerializer_get(book_list_obj,many=True) return Response(msg.data) def post(self,request): # post,put方法時,這個自定義序列裏面的參數是data=request.data,many msg = BookSerializer(data=request.data,many=False) if msg.is_valid(): msg.save() #create return Response(msg.data) else: return Response(msg.errors) class GetBookHandle(APIView): def put(self,request,id): book_obj = models.Book.objects.filter(pk=id).first() msg = BookSerializer(data=request.data,many=False,instance=book_obj) if msg.is_valid(): msg.save() return Response(msg.data) else : return Response(msg.errors) def delete(self,request,id): models.Book.objects.filter(pk=id).delete() return Response('') def get(self,request,id): book_obj = models.Book.objects.filter(pk=id).first() msg = BookSerializer_get(book_obj,many=False) return Response(msg.data) #################視圖組件############## class PublishSerializer(serializers.ModelSerializer): class Meta: model = models.Publish fields = '__all__' from rest_framework.mixins import ListModelMixin from rest_framework import generics class PublishHandel(ListModelMixin,generics.GenericAPIView): queryset = models.Publish.objects.all() serializer_class = PublishSerializer def get(self,request): return self.list(request)