restframework之序列化
序列化
序列化用于对用户请求数据进行验证和数据进行序列化(为了解决queryset序列化问题)。
那什么是序列化呢?序列化就是把对象转换成字符串,反序列化就是把字符串转换成对象
Django 序列化
serialze 只能做序列化,
from django.core.serializers import serialize
publish_list=Publish.objects.all()
#方式1: Django的序列化组件
# ret=serialize("json",publish_list)
我们用postman 帮我们提交数据
restframework 序列化(不只做序列化,可以集成)
如果是浏览器就是看到这个页面,如果是其他ajax就显示数据
具体代码
一,# 自定义序列化组件
Serializers:
from rest_framework import serializers #先把字段写出来 class BookSerializers(serializers.Serializer): title=serializers.CharField() price=serializers.CharField() publishDate=serializers.DateField() # 针对一对多 publish=serializers.CharField(source="publish.name") publish_email=serializers.CharField(source="publish.email") # 针对多对多 authors=serializers.SerializerMethodField() def get_authors(self,obj): data=[] for i in obj.authors.all(): temp=[] temp.append(i.pk) temp.append(i.name) data.append(temp) return data class PublishSerializers(serializers.Serializer): """ PublishSerializers组件是一个集成功能组件,到底用什么功能,取决于调用什么接口 """ name=serializers.CharField() # 普通字段 city=serializers.CharField() # email=serializers.EmailField() ''' ps=PublishSerializers(publish_list,many=True) # 序列化数据 return Response(ps.data) 解析: data=[] for obj in publish_list: data.append({ "name":obj.name, "city":obj.city, "email":obj.email, "publish":obj.publish.email, # if 字段是多对多字段: "authors":get_authors(obj) }) self.data=data '''
view:
from app01.models import * from django.core.serializers import serialize from rest_framework.views import APIView from app01.serializers import PublishSerializers,BookSerializers,AuthorSerializers from rest_framework.response import Response # 响应器 class PublishView(APIView): def get(self,request): publish_list=Publish.objects.all() #方式1: Django的序列化组件 # ret=serialize("json",publish_list) # 方式2:rest的序列化 ps=PublishSerializers(publish_list,many=True)# many=True:不仅仅是序列化queryset,还有model # 序列化数据 return Response(ps.data) def post(self,request): pass """ "books" GET:获取所有数据 POST:添加一条数据 "book/1" GET:获取单条数据 DELETE:删除一条数据 PUT/PATCH:更新一条数据 """" class BookView(APIView): def get(self, request): book_list = Book.objects.all() # 方式1: Django的序列化组件 # ret=serialize("json",publish_list) # 方式2:rest的序列化 bs = BookSerializers(book_list, many=True)# many=True:不仅仅是序列化queryset,还有model # 序列化数据 return Response(bs.data) def post(self, request): # 添加一条数据 print(request.data) # 添加数据 bs=BookSerializers(data=request.data) if bs.is_valid(): #校验字段接口 bs.save() # 生成记录 return Response(bs.data)# 序列化接口 else: return Response(bs.errors) class BookDetailView(APIView): def get(self,request,pk): book_obj=Book.objects.filter(pk=pk).first() bs=BookSerializers(book_obj,many=False) return Response(bs.data) def put(self,request,pk): book_obj = Book.objects.filter(pk=pk).first() # 更新数据 bs=BookSerializers(data=request.data,instance=book_obj) if bs.is_valid(): bs.save() # update return Response(bs.data) else: return Response(bs.errors) def delete(self,request,pk): Book.objects.filter(pk=pk).delete() return Response("")
二, ModelSerializer (不想写字段,可以直接继承)序列化组件
from app01.models import * class PublishSerializers(serializers.ModelSerializer): class Meta: model=Publish exclude=("nid",) from app01.models import * class BookSerializers(serializers.ModelSerializer): class Meta: model=Book fields="__all__" # publish = serializers.CharField(source="publish.name") # authors=serializers.SerializerMethodField() # def get_authors(self,obj): # data=[] # for i in obj.authors.all(): # temp=[] # temp.append(i.pk) # temp.append(i.name) # data.append(temp) # return data class AuthorSerializers(serializers.ModelSerializer): class Meta: model=Author fields="__all__"
Model 部分:
class Course(models.Model): title=models.CharField(max_length=32) from django.db import models # Create your models here. class Author(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max_length=32) age=models.IntegerField() # 与AuthorDetail建立一对一的关系 authorDetail=models.OneToOneField(to="AuthorDetail",on_delete=models.CASCADE) def __str__(self): return self.name class AuthorDetail(models.Model): nid = models.AutoField(primary_key=True) birthday=models.DateField() telephone=models.BigIntegerField() addr=models.CharField( max_length=64) def __str__(self): return str(self.telephone) class Publish(models.Model): nid = models.AutoField(primary_key=True) name=models.CharField( max_length=32) city=models.CharField( max_length=32) email=models.EmailField() def __str__(self): return self.name class Book(models.Model): nid = models.AutoField(primary_key=True) title = models.CharField( max_length=32) publishDate=models.DateField() price=models.DecimalField(max_digits=5,decimal_places=2) # 与Publish建立一对多的关系,外键字段建立在多的一方 publish=models.ForeignKey(to="Publish",to_field="nid",on_delete=models.CASCADE) # 与Author表建立多对多的关系,ManyToManyField可以建在两个模型中的任意一个,自动创建第三张表 authors=models.ManyToManyField(to='Author',) def __str__(self): return self.title
url:
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', views.LoginView.as_view()), url(r'^courses/$', views.CourseView.as_view()), url(r'^publishes/$', views.PublishView.as_view()), url(r'^books/$', views.BookView.as_view()), url(r'^books/(?P<pk>\d+)/$', views.BookDetailView.as_view()), url(r'^authors/$', views.AuthorView.as_view()), url(r'^authors/(?P<pk>\d+)/$', views.AuthorDetailView.as_view()), ]