一、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‘)
原文地址:https://www.cnblogs.com/qq631243523/p/10084134.html
时间: 2024-11-05 22:52:23