rest-framework框架
阿新 • • 發佈:2018-04-09
*args exclude sun rest 但我 size spa hit AR
快速搭建demo
view。py
主要將返回頁面的數據序列化為json數據
方式一: # class BookView(View): # def get(self,request,*args,**kwargs): # book_list = list(Book.objects.all().values("title","price")) # return HttpResponse(json.dumps((book_list))) 方式二: # class BookView(View): # def get(self,request,*args,**kwargs):# book_list = Book.objects.all() # list = [] # for book in book_list: # list.append({ # "title":book.title, # "price":book.price, # "pub_date":book.pub_date, # }) # # return HttpResponse(json.dumps(list))方式三 # 利用django的序列化serializers 會展示所有字段內容 # from django.core import serializers # class BookView(View): # def get(self,request,*args,**kwargs): # book_list = Book.objects.all() # temp = serializers.serialize("json",book_list) # return HttpResponse(temp) # 方式四 # rest-framework框架的序列化器 上面的只能處理發送瀏覽器的信息# 但我們需要處理發回服務器的數據
方式四,利用到了rest-framework框架的序列化器
都在view.py
1:需要繼承到框架裏面的APIView
from rest_framework.response import Response from rest_framework.views import APIView from django.core import serializers class BookView(APIView): def get(self,request,*args,**kwargs): book_list = Book.objects.all() # 將book_list轉換為json數據[{},{},{}} bs = BookSerializers(book_list,many=True) return Response(bs.data)
2:寫序列化組件
from rest_framework import serializers class BookSerializers(serializers.ModelSerializer): class Meta: model = Book fields = "__all__"
## exclude = [‘authors‘,] 排除,可以自定義
循環序列化樣式
‘‘‘ class BookSerializers(serializers.Serializer): title=serializers.CharField(max_length=32) price=serializers.IntegerField() pub_date=serializers.DateField() publish=serializers.CharField(source="publish.pk") authors=serializers.CharField() temp=[] for book in book_list: temp.append({ "title": book.title, "price": book.price, "pub_date": book.pub_date, "publish": book.publish.pk, "authors": book.authors, }) [ { "title": "python", "price": 123, "pub_date": "2018-04-08", "publish": "1" }, { "title": "go", "price": 222, "pub_date": "2018-04-08", "publish": "2" }, ] ‘‘‘cbv的view是django apiview也是繼承django的view
避免csrf方式
方式一 將中間件的csrf註釋 (全局)方式二 (局部)
rest-framework框架