DjangoRestFramework之序列化组件

Posted attila

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DjangoRestFramework之序列化组件相关的知识,希望对你有一定的参考价值。

一 . serializers

from rest_framework.views import APIView
from app01 import models
from rest_framework.response import Response
from rest_framework import serializers

# 使用serializers 需要先定义一个类,类里面的内容要和models一致
class BookSerializers(serializers.Serializer):
    title = serializers.CharField(max_length=16)
    price = serializers.IntegerField()

class BookHandle(APIView):

    def get(self, request):
        book_msg = models.Books.objects.all()
        res = BookSerializers(book_msg, many=True)  # 当res里面有多个对象(query_set)的时候要指定many=true(必填)
        print(res.data)
        return Response(res.data)  # 可以用rest_framework里面的Response

    def post(self, request):
        # print(‘post方法==>‘, request.data)
        res = BookSerializers(data=request.data, many=False)
        if res.is_valid():  # 这个是对传过来数据与models里面的字段是否对应进行验证
            models.Books.objects.create(**res.data)
            return Response(res.data)  # 按照API接口规范,数据存储成功后要返回
        return Response(res.errors)

二 . 学了单表的,来一波跨表的序列化 

from django.db import models

class Author(models.Model):
    nid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    age = models.IntegerField()

class AuthorDetail(models.Model):
    nid = models.AutoField(primary_key=True)
    birthday = models.DateField()
    telephone = models.BigIntegerField()
    addr = models.CharField(max_length=64)

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()

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 = models.ForeignKey(to="Publish", to_field="nid", on_delete=models.CASCADE)  # 多对一到Publish表
    authors = models.ManyToManyField(to=Author, )  # 多对多到Author表

 

技术图片
 1 from rest_framework.response import Response
 2 from rest_framework.views import APIView
 3 from rest_framework import serializers
 4 from app01 import models
 5 
 6 class BookSerializer(serializers.Serializer):
 7     title = serializers.CharField(max_length=32)
 8     price = serializers.DecimalField(max_digits=5, decimal_places=2)
 9     # 如果不写source拿到的是object,想要哪个字段,就在source后面写对应表的字段,
10     publish_name = serializers.CharField(source=publish.name)  # book表中publish外键
11     publish_city = serializers.CharField(source=publish.city)
12     # 多对多的用法
13     authors = serializers.SerializerMethodField(source=authors.all)  # 拿到的是query-set对象
14 
15     def get_authors(self, obj):  # 函数名格式必须是get_这个类中对应的属性名,obj就是下面book_obj_list里的每一个对象
16         lst = []
17         authors_list = obj.authors.all()
18         for author in authors_list:
19             dic = {}
20             dic[name] = author.name
21             lst.append(dic)
22         return lst
23 
24 class BookHandle(APIView):
25     # 获取所有数据
26     def get(self, request):
27         book_obj_list = models.Book.objects.all()
28         book_res = BookSerializer(book_obj_list, many=True)
29         return Response(book_res.data)
30 
31     def post(self, request):
32         pass
视图函数

 

  多对一的外键序列化展示,在没有写source之前

 技术图片

  写了source之后

  技术图片

  多对多的外键序列化展示

  

  技术图片

  技术图片

 

 

  

 

以上是关于DjangoRestFramework之序列化组件的主要内容,如果未能解决你的问题,请参考以下文章

DRF之解析器组件及序列化组件

DjangoRestFramework之认证组件,权限组件,频率组件

DjangoRestFramework学习三之认证组件权限组件频率组件url注册器响应器分页组件

DRF - 解析器组件

django rest framework的十个组件

Serializer组件