CBV 序列化

一、模型表

from django.db import models

# Create your models here.


class Publish(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=128)

    def __str__(self):
        return self.name


class Book(models.Model):
    title = models.CharField(max_length=16)
    price = models.DecimalField(max_digits=4, decimal_places=2)
    publisher = models.ForeignKey(to="Publish", on_delete=models.CASCADE)
    authors = models.ManyToManyField(to="Author")

    def __str__(self):
        return self.title


class Author(models.Model):
    name = models.CharField(max_length=8)
    email = models.CharField(max_length=36)

    def __str__(self):
        return self.name

二、序列化

1、json 强转QuerySet->list

class TestView(View):
    def get(self, request):
        print(request.GET)
        return render(request, "test.html")
        # return HttpResponse("get")

    def post(self, request):
        import json
        publish_list = list(Publish.objects.all().values("name", "addr"))
        return HttpResponse(json.dumps(publish_list, ensure_ascii=False))

2、json 构建新的

from django.shortcuts import render, HttpResponse
from django.views import View
from CBV.models import Publish, Book, Author
from rest_framework import serializers

# Create your views here.


class PublishSer(serializers.Serializer):
    name = serializers.CharField()
    addr = serializers.CharField()


class TestView(View):
    def get(self, request):
        print(request.GET)
        return render(request, "test.html")
        # return HttpResponse("get")

    def post(self, request):
        publish_list = Publish.objects.all()
        temp = []
        for publish in publish_list:
            temp.append({
                "name": publish.name,
                "addr": publish.addr,
            })
        print(temp)
        return HttpResponse(temp)
        # 结果:{'name': '北京出版社', 'addr': '北京'}{'name': '南京出版社', 'addr': '南京'}

优化

from django.shortcuts import render, HttpResponse
from django.views import View
from CBV.models import Publish, Book, Author
from rest_framework import serializers
from django.forms import model_to_dict
# Create your views here.


class PublishSer(serializers.Serializer):
    name = serializers.CharField()
    addr = serializers.CharField()


class TestView(View):
    def get(self, request):
        print(request.GET)
        return render(request, "test.html")
        # return HttpResponse("get")

    def post(self, request):
        publish_list = Publish.objects.all()
        temp = []
        for publish in publish_list:
            temp.append(model_to_dict(publish))
        print(temp)
        return HttpResponse(temp)
        # 结果:{'name': '北京出版社', 'addr': '北京'}{'name': '南京出版社', 'addr': '南京'}

注意:from djang.forms import model_to_dict

3、Django序列化

class TestView(View):
    def get(self, request):
        print(request.GET)
        return render(request, "test.html")
        # return HttpResponse("get")

    def post(self, request):
        # 方法3
        from django.core import serializers
        publish_list = Publish.objects.all()
        print(publish_list)
        # serialize里面添加的是queryset
        publish_json = serializers.serialize('json', publish_list)
        return HttpResponse(publish_json)
        # 结果: [{"model": "CBV.publish", "pk": 1, "fields": {"name": "\u5317\u4eac\u51fa\u7248\u793e", "addr": "\u5317\u4eac"}}, {"model": "CBV.publish", "pk": 2, "fields": {"name": "\u5357\u4eac\u51fa\u7248\u793e", "addr": "\u5357\u4eac"}}]

4、rest_framwork

from django.shortcuts import render, HttpResponse
from django.views import View
from CBV.models import Publish, Book, Author
from rest_framework import serializers

# Create your views here.


class PublishSer(serializers.Serializer):
    name = serializers.CharField()
    addr = serializers.CharField()


class TestView(View):
    def get(self, request):
        print(request.GET)
        return render(request, "test.html")
        # return HttpResponse("get")

    def post(self, request):
        publish_list = Publish.objects.all()
        ret = PublishSer(publish_list, many=True)
        return HttpResponse(ret.data)
        # 结果:OrderedDict([('name', '北京出版社'), ('addr', '北京')])OrderedDict([('name', '南京出版社'), ('addr', '南京')])

注意:若序列化的是一个obj,那么many=False(默认),list many=True

 三、request

A、Django 原生的request

浏览器 ------------> 服务器

浏览器发送请求到服务器

1、POST

POST的Request Heads 的 Content-Type: application/x-www-form-urlencoded

只有contenttype 是 urlencode时,才会转化成QueryDict

2、body

直接捕获请求的content,如:b'{\n\t"name":"tom",\n\t"age":18\n}'

 B、rest_framework 的request

1、data

获取POST任意contenttype的数据,并反序列化

2、other

request._request.GET 也可以 request.GET

posted @ 2019-09-03 16:27  市丸银  阅读(136)  评论(0编辑  收藏  举报