标签:http author meta length img get 中间件 会展 技术
快速搭建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" }, ] ‘‘‘
标签:http author meta length img get 中间件 会展 技术
原文地址:https://www.cnblogs.com/jassin-du/p/8757521.html