整理和序列化serialize和视图类APIView相关的代码
目录
book表
一、先建好好modelsbook表模型
from django.db import models
# Create your models here.
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.CharField(max_length=32)
publish = models.ForeignKey(to='Publish',
on_delete=models.SET_NULL,
null=True)
authors = models.ManyToManyField(to='Author')
class Publish(models.Model):
name = models.CharField(max_length=32)
addr = models.CharField(max_length=32)
class Author(models.Model):
name = models.CharField(max_length=32)
phone = models.CharField(max_length=11)
author_detail = models.OneToOneField(to='AuthorDetail',
on_delete=models.CASCADE)
class AuthorDetail(models.Model):
email = models.CharField(max_length=32)
age = models.IntegerField()
二、在serialize文件中写继承serializers.ModelSerializer的BookSerializer类
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ['name', 'price', 'publish_detail', 'author_list', 'publish', 'authors'] # 自定制的字段,一定要在这里注册一下
extra_kwargs = {
'name': {'max_length': 10, 'required': True},
'publish': {'write_only': True},
'authors': {'write_only': True}
}
publish_detail = serializers.DictField(read_only=True)
author_list = serializers.ListField(read_only=True)
三、在视图view中写BookView类的增删查改
from django.shortcuts import render
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Book
from .serializer import BookSerializer
class BookView(APIView):
def get(self, request):
qs = Book.objects.all()
ser = BookSerializer(qs, many=True)
return Response({'code': 100,
'mag': '成功',
'results': ser.data})
def post(self, request):
ser = BookSerializer(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 = BookSerializer(book)
return Response({'code': 100,
'msg': '成功',
'results': ser.data})
def put(self, request, pk):
book = Book.objects.get(pk=pk)
ser = BookSerializer(data=request.data,instance=book)
if ser.is_valid():
ser.save()
return Response({'code': 100,
'msg': '更新成功'})
else:
return Response({'code': 100,
'msg': ser.errors})
Author表
一、这里可读可写没有限制,因为字典忘记咋切成一分为二的
二、在serialize文件中写继承serializers.ModelSerializer的AuthorSerializer类,以及新写的create和update方法
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ['id', 'name', 'phone', 'email', 'age',]
# 不是表的字段,一定要重写
email = serializers.CharField(source='author_detail.email')
age = serializers.IntegerField(source='author_detail.age')
# email = serializers.CharField(write_only=True)
# age = serializers.IntegerField(write_only=True)
def create(self, validated_data):
# 校验过得数据
print(validated_data)
author_detail = validated_data.pop('author_detail')
print(author_detail)
author_detail_obj = AuthorDetail.objects.create(**author_detail)
# 先给Author表中的detail_id create新id
validated_data['author_detail_id'] = author_detail_obj.pk
author = Author.objects.create(**validated_data)
return author
def update(self, instance, validated_data):
instance.name = validated_data.get('name')
instance.phone = validated_data.get('phone')
print(validated_data)
print(instance)
instance.author_detail.email = validated_data.get('author_detail').get('email')
instance.author_detail.age = validated_data.get('author_detail').get('age')
instance.save()
instance.author_detail.save()
return instance
三、视图层
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Book,Publish,Author,AuthorDetail
from .serializer import BookSerializer,PublishSerializer,AuthorSerializer
class AuthorView(APIView):
def get(self, request):
qs = Author.objects.all()
ser = AuthorSerializer(qs, many=True)
return Response({'data': ser.data})
def post(self, request):
ser = AuthorSerializer(data=request.data)
if ser.is_valid():
ser.save()
return Response({'code': 100,
'msg': '成功'})
else:
return Response({'code': 101,
'msg': '失败'})
class AuthorDetailView(APIView):
def get(self, request, pk):
book = Author.objects.all().get(pk=pk)
ser = AuthorSerializer(book)
return Response({'code': 100,
'msg': '成功'})
def put(self, request, pk):
author = Author.objects.get(pk=pk)
ser = AuthorSerializer(data=request.data,instance=author)
if ser.is_valid():
ser.save()
return Response({'code':100,
'msg': '成功','data':ser.data})
else:
return Response({'code':101,
'msg': ser.errors,
})
def delete(self,request, pk):
author = Author.objects.filter(pk=pk).first()
AuthorDetail.objects.filter(pk=author.author_detail.id).delete()
return Response({'code': 100,'msg': '成功', })
四、路由层
path('author/', views.AuthorView.as_view()),
path('author/<int:pk>/', views.AuthorDetailView.as_view()),