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

DjangoRestFramework之序列化组件

时间:2019-05-02 15:38:54      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:pass   birt   query   response   cli   for   serial   ror   inf   

一 . 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之序列化组件

标签:pass   birt   query   response   cli   for   serial   ror   inf   

原文地址:https://www.cnblogs.com/attila/p/10802342.html

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