Python微信订餐小程序课程视频
https://edu.csdn.net/course/detail/36074
Python实战量化交易理财系统
https://edu.csdn.net/course/detail/35475
今日内容概要
- 序列化多表操作
- 请求与相应
- 视图组件
内容详细
1、序列化多表操作
模型类 models.py中
# 新建django项目
# 创建表 模型类models.py中:
from django.db import models
# 4张表
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=5, decimal_places=2)
publish = models.ForeignKey(to='Publish', on_delete=models.CASCADE) # to='Publish' 自动关联publish表主键 // on\_delete=models.CASCADE 级联删除
authors = models.ManyToManyField(to='Author')
def \_\_str\_\_(self):
return self.name
@property
def publish\_detail(self): # 定制字段
return {'name': self.publish.name, 'addr': self.publish.city}
@property
def author\_list(self): # 定制字段
l = []
# print(self.authors.all())
for author in self.authors.all():
# print(author.author\_detail)
l.append({'name': author.name, 'age': author.age, 'addr': author.author_detail.addr})
return l
class Author(models.Model):
name = models.CharField(max_length=32)
age = models.IntegerField()
author_detail = models.OneToOneField(to='AuthorDatail', on_delete=models.CASCADE)
# OneToOneField 就是 ForeignKey + unique=True
class AuthorDatail(models.Model):
telephone = models.BigIntegerField()
addr = models.CharField(max_length=64)
class Publish(models.Model):
name = models.CharField(max_length=32)
city = models.CharField(max_length=32)
email = models.EmailField()
"""
在每个表中写入数据一一对应
第五个自动创建的关联表 也写入数据
"""
创建序列化类 serializer.py
from .models import *
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
# fields = '\_\_all\_\_'
fields = ['id', 'name', 'price', 'authors', 'publish', 'publish\_detail', 'author\_list']
# 由于前端的publis