码迷,mamicode.com
首页 > 其他好文 > 详细

第85篇 Vue第六篇 Rest_Framework序列化与反序列化 Serializers

时间:2018-12-10 22:06:09      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:svi   validate   获取   save   pat   第二版   alt   integer   序列   

 

models.py

from django.db import models

# Create your models here.
__all__ = ["Book", "Publisher", "Author"]


class Book(models.Model):
    title = models.CharField(max_length=32)
    CHOICES = ((1, "python"), (2, "linux"), (3, "go"))
    category = models.IntegerField(choices=CHOICES)
    pub_time = models.DateField()
    publisher = models.ForeignKey(to="Publisher")
    authors = models.ManyToManyField(to="Author")


class Publisher(models.Model):
    title = models.CharField(max_length=32)



class Author(models.Model):
    name = models.CharField(max_length=32)

 serializers.py

from rest_framework import serializers
from .models import Book


class PublisherSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField(max_length=32)
    

class AuthorSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField(max_length=32)


class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False)
    title = serializers.CharField(max_length=32)
    pub_time = serializers.DateField()
    # CHOICES = ((1, "python"), (2, "linux"), (3, "go"))
    # category = serializers.ChoiceField(choices=CHOICES)
    category = serializers.CharField(source="get_category_display", read_only=True)
    post_category = serializers.IntegerField(write_only=True)
    
    publisher = PublisherSerializer(read_only=True)
    authors = AuthorSerializer(many=True, read_only=True)

    publisher_id = serializers.IntegerField(write_only=True)
    author_list = serializers.ListField(write_only=True)


    def create(self, validated_data):
        #通过ORM操作给Book表增加数据
        print(validated_data)
        book_obj = Book.objects.create(title=validated_data["title"], pub_time=validated_data["pub_time"],
                            category=validated_data["post_category"], publisher_id=validated_data["publisher_id"])
        book_obj.authors.add(*validated_data["author_list"])
        return book_obj

  urls.py

from django.conf.urls import url, include
from .views import BookView, BooksView, BookEditView

urlpatterns = [
    # url(r‘^list$‘, BookView.as_view()),
    url(r‘^list$‘, BooksView.as_view()),
    url(r‘^retrieve/(?P<id>\d+)$‘, BookEditView.as_view()),
]

  views.py

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, JsonResponse
from .models import Book, Publisher
from django.core import serializers
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import serializers
from .serializers import BookSerializer
import json
# Create your views here.

# book_list = [
#     {
#         "id": 1,
#         "title": "",
#         "publisher": {
#              "id": 1
#               "title": ""
#           },
#          "authors": [{}]
#     },
#     {
#
#     }
# ]


class BookView(View):
    # 第一版用.values实现序列化
    # def get(self, request):
    #     book_queryset = Book.objects.values("id", "title", "pub_time", "publisher")
    #     # queryset [{}, {}]
    #     book_list = list(book_queryset)
    #     ret = json.dumps(book_list, ensure_ascii=False)
        # return HttpResponse(ret)
    #     ret = []
    #     for book in book_list:
    #         publisher_obj = Publisher.objects.filter(id=book["publisher"]).first()
    #         book["publisher"] = {
    #             "id": publisher_obj.id,
    #             "title": publisher_obj.title
    #         }
    #         ret.append(book)
    #     return JsonResponse(ret, safe=False, json_dumps_params={"ensure_ascii": False})

    # 第二版
    def get(self, request):
        book_queryset = Book.objects.all()
        ret = serializers.serialize("json", book_queryset, ensure_ascii=False)
        return HttpResponse(ret)


class BooksView(APIView):
    def get(self, request):
        # print(request._request)
        book_queryset = Book.objects.all()
        # 声明一个序列化器
        # 用序列化器去序列化queryset
        ser_obj = BookSerializer(book_queryset, many=True)
        return Response(ser_obj.data)

    # 前端 {"id""title",
    #         category: 1
    #           publisher: 1
    #           authors: [1, 2]
    #       }
    def post(self, request):
        # 获取前端传过来的数据
        book_obj = request.data
        # 用序列化器做校验
        ser_obj = BookSerializer(data=book_obj)
        if ser_obj.is_valid():
            ser_obj.save()
            print(ser_obj.validated_data)
            return Response(ser_obj.data)
        return Response(ser_obj.errors)


class BookEditView(APIView):
    def get(self, request, id):
        book_obj = Book.objects.filter(id=id).first()
        pass

    # {"title": "xxxx"}

    def put(self, request, id):
        pass


		
		
		
		
		
		
		
		
		
		
		

  

 

 

 

APIView跟View区别
-- APIView继承了View
-- scrf的豁免
-- 重新封装了request
旧的request给了request._request
request.query_params 旧的request.GET
request.data 除了GET的所有的信息

技术分享图片

 

技术分享图片

 


序列化组件
-- 序列化
--一定要记得在setting.py 中的app里面加上rest_framework ←这个很重要
-- 声明一个序列化器
class BookSerializer(serializers.Serializer):
id = serializers.IntegerField(required=False)
title = serializers.CharField(max_length=32)
pub_time = serializers.DateField()
-- 视图里序列化我们的queryset
ser_obj = BookSerializer(queryset, many=True)
return Response(ser_obj.data)
-- 实现流程
-- 如果指定了many=True
-- 把queryset当成可迭代对象去循环 得到每个模型对象
-- 把每个模型对象放入序列号器进行序列化
-- 进行字段匹配 匹配上的字段进行序列化 匹配不上丢弃
-- 必须满足序列化的所有字段要求
-- 反序列化
-- 获取前端传过来的数据
-- 用序列化器进行校验
ser_obj = BookSerializer(data=request.data)
if ser_obj.is_valid():
ser_obj.save()# 调用create方法
return Response(ser_obj.data)
else:
return Response(ser_obj.errors)
-- 写create方法
在create方法里用ORM操作创建新对象
-- 序列化以及反序列化的时候字段类型不统一的情况
-- required=False
-- read_only=True
-- write_only=True

第85篇 Vue第六篇 Rest_Framework序列化与反序列化 Serializers

标签:svi   validate   获取   save   pat   第二版   alt   integer   序列   

原文地址:https://www.cnblogs.com/cavalier-chen/p/10099024.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!