rest-framework序列化
将数据显示到页面上,在后端需要对其及进行序列化处理
参考文档:https://www.cnblogs.com/glh-ty/p/9671397.html
1.用原生的HttpResponse处理
from django.views import View from app01 import models import json class BookView(View): def get(self,request): book_obj=models.Book.objects.all() #将每个对象都取出来,放到列表中,序列化后返回 temp=[] for obj in book_obj: temp.append({ "pk":obj.pk, "title":obj.title }) return HttpResponse(json.dumps(temp))
2.使用rest_framework的响应处理
from rest_framework.response import Response class BookView(View): def get(self,request): book_obj=models.Book.objects.all() #将每个对象都取出来,放到列表中,序列化后返回 temp=[] for obj in book_obj: temp.append({ "pk":obj.pk, "title":obj.title }) return Response(json.dumps(temp))
同时在INSTALLED_APPS加入"rest_framework",上述方法不足之处:当字段很多时,我们要写入多个字段,不方便
使用restframework进行序列化
方法一:model_to_dict(obj)
class BookView(APIView): def get(self,request): book_obj=models.Book.objects.all() from django.forms.models import model_to_dict temp = [] for book in book_obj: temp.append(model_to_dict(book)) return Response(json.dumps(temp)) 页面显示:"[{\"id\": 2, \"title\": \"python\"}, {\"id\": 3, \"title\": \"go\"}]"
方法二:serialize
class BookView(APIView):
def get(self,request):
book_obj=models.Book.objects.all()
from django.core.serializers import serialize
ret=serialize("json",book_obj)
return Response(ret)
"[{\"model\": \"app01.book\", \"pk\": 2, \"fields\": {\"title\": \"python\"}},
{\"model\": \"app01.book\", \"pk\": 3, \"fields\": {\"title\": \"go\"}}]"
方法三:序列化组件 rest_framework组件中serializers,使用如同form组件:
不仅可以序列化queryset也可以序列化对象
自定义类,继承serializers
rom rest_framework import serializers class BookSerializers(serializers.Serializer): title=serializers.CharField(max_length=32)
class BookView(APIView): def get(self,request): book_list=models.Book.objects.all() bs = BookSerializers(book_list, many=True) return Response(bs.data)
如果要显示其他的字段就在BookSerializers设定其他的字段
在设定ForeignKey和ManyToManyField的操作:
ForeignKey:
publish=serializers.CharField(max_length=32,source="publish.name")
设置source,可任意设置要显示的对象属性。如果模型表中国没设置返回name,这里也没设置source
则显示:
{ "title": "python", "price": "110.00", "publish": "Publish object" }
ManyToManyField:
如果使用ForeignKey的显示方式,则应该:
authors=serializers.CharField(max_length=32,source="authors.all")
页面上的作者显示的都是具体的对象:
[ { "title": "python", "price": "110.00", "publish": "北京出版社", "authors": "<QuerySet [<Author: jerd>, <Author: jerry>]>" }, { "title": "go", "price": "110.00", "publish": "天青烟雨出版社", "authors": "<QuerySet [<Author: jerry>]>" } ]
而我们需要显示的是对应的作者对象姓名,定义get_+字段名函数
authors=serializers.SerializerMethodField() def get_authors(self,obj): temp=[] for obj in obj.authors.all(): temp.append(obj.name) return temp
[ { "title": "python", "price": "110.00", "publish": "北京出版社", "authors": [ "jerd", "jerry" ] }, { "title": "go", "price": "110.00", "publish": "天青烟雨出版社", "authors": [ "jerry" ] } ]
bs=BookSerializers(book_list,many=True)的效果等同于
temp=[] for obj in book_list: temp.append({ 'title':obj.title, 'price':obj.price, 'publish':obj.publish.name, 'authors': }) bs.data=json.dumps(temp)