drf——多表关联的反序列化之保存与修改
序列化的字段有:name,price ,publish_detail,author_list
反序列化字段:name,price ,publish,author
视图类:
class BookView(APIView): def post(self, request): ser = BookSerialzier(data=request.data) if ser.is_valid(): ser.save() return Response({'code': 100, 'msg': '成功'}) else: return Response({'code': 100, 'msg': ser.errors})
序列化类:
class BookSerialzier(serializers.Serializer): # 即用来做序列化,又用来做反序列化 name = serializers.CharField(max_length=8) price = serializers.CharField() # 这俩,只用来做序列化 publish_detail = serializers.DictField(read_only=True) # 只读 author_list = serializers.ListField(read_only=True) # 这俩,只用来做反序列化 publish_id = serializers.IntegerField(write_only=True) # 只写 authors = serializers.ListField(write_only=True) def create(self, validated_data): # {name:西游记,price:88,publish:1,authors:[1,2] authors = validated_data.pop('authors') book = Book.objects.create(**validated_data) book.authors.add(*authors) return book
反序列化之修改
视图类
class BookDetailView(APIView): def put(self, request,pk): book=Book.objects.get(pk=pk) ser = BookSerialzier(data=request.data,instance=book) if ser.is_valid(): ser.save() return Response({'code': 100, 'msg': '更新成功'}) else: return Response({'code': 100, 'msg': ser.errors})
序列化类
class BookSerialzier(serializers.Serializer): # 即用来做序列化,又用来做反序列化 name = serializers.CharField(max_length=8) price = serializers.CharField() # 这俩,只用来做序列化 publish_detail = serializers.DictField(read_only=True) author_list = serializers.ListField(read_only=True) # 这俩,只用来做反序列化 publish_id = serializers.IntegerField(write_only=True) authors = serializers.ListField(write_only=True)
视图层代码书写:
from django.shortcuts import render # Create your views here. from rest_framework.views import APIView from .serializer import BookSerialzier from rest_framework.response import Response from .models import Book class BookView(APIView): def get(self, request): qs = Book.objects.all() ser = BookSerialzier(qs, many=True) return Response({'code': 100, 'msg': '成功', 'results': ser.data}) def post(self, request): ser = BookSerialzier(data=request.data) if ser.is_valid(): ser.save() return Response({'code': 100, 'msg': '成功'}) else: return Response({'code': 100, 'msg': ser.errors}) class BookDetailView(APIView): def get(self, request, pk): book = Book.objects.all().get(pk=pk) ser = BookSerialzier(book) return Response({'code': 100, 'msg': '成功', 'results': ser.data}) def put(self, request,pk): book=Book.objects.get(pk=pk) ser = BookSerialzier(data=request.data,instance=book) if ser.is_valid(): ser.save() return Response({'code': 100, 'msg': '更新成功'}) else: return Response({'code': 100, 'msg': ser.errors})