序列化组件
Posted xujinjin18
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了序列化组件相关的知识,希望对你有一定的参考价值。
序列化组件
把后端的数据对象序列化成json格式的字符串传到前端
一 Django内置的serializers(把对象序列化成json字符串)
from django.core import serializers
from django.core import serializers def test(request): book_list = Book.objects.all() ret = serializers.serialize("json", book_list) return HttpResponse(ret)
###
二 rest-framework序列化之Serializer
models部分:
from django.db import models # Create your models here. class Book(models.Model): title=models.CharField(max_length=32) price=models.IntegerField() pub_date=models.DateField() publish=models.ForeignKey("Publish") authors=models.ManyToManyField("Author") def __str__(self): return self.title class Publish(models.Model): name=models.CharField(max_length=32) email=models.EmailField() def __str__(self): return self.name class Author(models.Model): name=models.CharField(max_length=32) age=models.IntegerField() def __str__(self): return self.name
view部分:
from django.shortcuts import render,HttpResponse # Create your views here. from api import models from rest_framework.views import APIView #API from rest_framework import serializers #序列化 from rest_framework.response import Response #前端有样式 # 如果要用rest_framework的序列化,必须写一个类 class BookSerializer(serializers.Serializer): # 如果想重命名,指定source xx=serializers.CharField(source=‘title‘) price=serializers.CharField() pub_date=serializers.DateField() publish=serializers.CharField(source=‘publish.email‘) #这个拿到的是publish表里的email字段值 # publish=serializers.CharField() #外键,这个拿到的是对象 class Book(APIView): def get(self,request): # request.data ret=models.Book.objects.all() # ret 是queryset对象,many=True代表序列化多条,many=False 代表序列化一条 book_ser=BookSerializer(ret,many=True) print(book_ser.data) #序列化完成后的字典 return Response(book_ser.data) #带样式 # return HttpResponse(json.dumps(book_ser.data)) def post(self,request): print(request.data) print(request.POST) return HttpResponse(‘ok‘)
以上是关于序列化组件的主要内容,如果未能解决你的问题,请参考以下文章