多表序列化,请求与响应
作者:互联网
多表序列化
urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('books/',views.Books.as_view()),
path('books/<int:pk>',views.Booksid.as_view()),
]
models.py
from django.db import models
# Create your models here.
class Book(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
# publish_date = models.DateField(null=True)
# 关联关系
publish = models.ForeignKey(to='Publish', to_field='nid', on_delete=models.CASCADE)
authors = models.ManyToManyField(to='Author') # 自动生成中间表
def publish_detail(self):
return {'name':self.publish.name,'city':self.publish.city}
def author_list(self):
list1 = []
for author in self.authors.all():
list1.append(author.name)
return list1
def __str__(self):
return self.name
class Author(models.Model):
nid = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
age = models.IntegerField()
author_detail = models.OneToOneField(to='AuthorDetail', on_delete=models.CASCADE)
def __str__(self):
return self.name
class AuthorDetail(models.Model):
nid = models.AutoField(primary_key=True)
telephone = models.BigIntegerField()
birthday = models.DateField()
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()
def __str__(self):
return self.name
serializer.py
from app01 import models
from rest_framework import serializers
class BooksSerializer(serializers.ModelSerializer):
class Meta:
model = models.Book
#方法一
# fields = ['nid', 'name', 'price', 'publish_detail', 'author_list', 'publish', 'authors']
# extra_kwargs = {
# 'publish': {'write_only': True},
# 'authors': {'write_only': True},
# }
###########################################################################################################
#方法二:在表模型models中写方法,在序列化类中写到fields中
fields = ['nid', 'name', 'price', 'publish', 'authors' , 'publish_detail','author_list']
extra_kwargs = {
'publish': {'write_only': True},
'authors': {'write_only': True},
'publish_detail':{'read_only':True},
'author_list':{'read_only':True},
}
# 方法一:重写字段+必须配合一个方法,方法返回啥,该字段就是什么--->该字段只能序列化
# publish_detail = serializers.SerializerMethodField(read_only=True)
#
# def get_publish_detail(self, book):
# return {'name': book.publish.name, 'city': book.publish.city}
#
# author_list = serializers.SerializerMethodField(read_only=True)
#
# def get_author_list(self, obj):
# author_list = []
# for author in obj.authors.all():
# author_list.append(author.name)
# return author_list
views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
# Create your views here.
from .models import Book
from .serialzer import BooksSerializer
class Books(APIView):
def get(self,request):
books = Book.objects.all()
ser = BooksSerializer(instance=books,many=True)
return Response(ser.data)
def post(self,request):
ser = BooksSerializer(data=request.data)
if ser.is_valid():
ser.save()
return Response({'code':'200','msg':'添加成功'})
else:
return Response({'code': '201', 'msg': '添加失败', 'errors': ser.errors})
class Booksid(APIView):
def get(self,request,pk):
book = Book.objects.filter(pk=pk).first()
ser = BooksSerializer(instance=book,many=False)
return Response(ser.data)
def put(self,request,pk):
book = Book.objects.all().filter(pk=pk).first()
ser = BooksSerializer(instance=book,data=request.data)
if ser.is_valid():
ser.save()
return Response({'code':'200','msg':'修改成功标签:多表,name,models,self,publish,响应,return,序列化,True
来源: https://www.cnblogs.com/chunyouqudongwuyuan/p/16382777.html