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

RestFramework之序列化组件

时间:2018-12-07 21:12:47      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:取数据   对象   模块   app   ted   creat   max   for   success   

一、restframework的序列化组件的使用

  1.导入序列化组件与模型类

from rest_framework import serializers
from app01.models import (
    Book,
    Author,
    Publish
)

 

  2.书写序列化类

  

# 创建一个序列化类


class BookSerializer(serializers.Serializer):
    ‘‘‘
    开始使用序列化
        - 导入模块:from rest_framework import serializers
        - 建立一个序列化类
            class BookSerializer(serializers.Serializer):
            字段可以自定义
        - 获取queryset
            origin_data = Book.objects.all()
        - 开始序列化
            serialized_data = BookSerializer(origin_data, many=True)
        - 获取序列化后的数据,返回给客户端
            return Response(serialized_data.data)
    ‘‘‘
    title = serializers.CharField(max_length=32)
    price = serializers.DecimalField(max_digits=5,decimal_places=2)
    publish = serializers.CharField(max_length=32)

    # 多对多字段需要自己手动获取数据,SerializerMethodField()
    author_list = serializers.SerializerMethodField()

    def get_author_list(self,obj):
        ‘‘‘
        处理多对多关系
        :param obj: Book对象
        :return:
        ‘‘‘
        #定义作者列表对象
        author_list =list()
        # print(obj.authors.all())
        for author in obj.authors.all():
            author_list.append(author.name)
        return author_list

    def create(self, validated_data):
        # {‘title‘: ‘Python666‘, ‘price‘: Decimal(‘66.00‘), ‘publish‘: ‘2‘}
        validated_data[publish_id] = validated_data.pop(publish)

        book = Book.objects.create(**validated_data)

        return book
# 基于ModelSerializer书写的序列化类
class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = __all__
        extra_kwargs={
            publish:{write_only:True},
            authors:{write_only:True}
        }
    publish_name = serializers.CharField(max_length=32,source=publish.name,read_only=True)
    publish_place = serializers.CharField(max_length=32,source=publish.place,read_only=True)

    author_list = serializers.SerializerMethodField()

    def get_author_list(self,obj):
        author_list=[]
        for author in obj.authors.all():
            author_list.append(
                author.name
            )
        return author_list

  3.视图中的用法

    首先也是要导入restframework中封装view的APIview与响应方式

from rest_framework.views import APIView
from rest_framework.response import Response

    然后书写视图类

class BookListView(APIView):
    # 获取全部
    def get(self,request):
        ‘‘‘
        1.获取queryset对象
        2.开始序列化,给序列化类传值(quertset)
        3.返回Response(.data)
        :param request:
        :return:
        ‘‘‘
        data = Book.objects.all()
        serializer_data = BookSerializer(data,many=True)
        return Response(serializer_data.data)
    # 添加
    def post(self,request):
        bs = BookSerializer(data=request.data)
        print(bs)
        if bs.is_valid():
            book = bs.save()
            authors = Author.objects.filter(id__in=request.data[authors])
            book.authors.add(*authors)
            return Response(bs.data)
        else:
            return Response(bs.errors)

class BookFileView(APIView):
    # 获取一条
    def get(self,request,pk):
        book_obj = Book.objects.get(pk=pk)
        bs = BookSerializer(book_obj ,many=False)
        return Response(bs.data)
    # 修改
    def put(self,request,pk):
        book_obj = BookSerializer(pk=pk)
        bs = BookSerializer(data=request.data,instance=book_obj)
        if bs.is_valid():
            bs.save()
            return Response(bs.data)
        else:
            return Response(bs.errors)
    # 删除
    def delete(self,request,pk):
        Book.objects.get(pk=pk).delete()
        return Response(Delete operation successfully)

  

  

RestFramework之序列化组件

标签:取数据   对象   模块   app   ted   creat   max   for   success   

原文地址:https://www.cnblogs.com/qq631243523/p/10084134.html

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