1 图书表:book,作者表:author,作者详情表:authordetail,出版社表:publish,(第三张中间表)
2 作者跟作者详情:是一对一,关联字段写在哪一方都可以
3 图书跟出版社:是一对多,一对多关系一旦确立,关联字段写在多的一方
4 图书和作者:是多对多,多对多的关系需要建立第三张表(可以自动生成)
5 models.py中把关系建立出来
from django.db import models
### django: 1.11.1 2.0.7
# Create your models here.
class Publish(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
addr = models.CharField(max_length=64)
phone = models.CharField(max_length=64)
email = models.EmailField()
class Book(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
price = models.DecimalField(max_digits=6, decimal_places=2)
publish_date = models.DateTimeField(auto_now_add=True)
# to='Publish'跟Publish表做关联(ForeignKey,一对多)
# to_field='id'跟哪个字段做关联
# publish=models.CharField(max_length=32)
# publish=models.ForeignKey(to='Publish',to_field='id')
# publish = models.ForeignKey(to='Publish') # 不写,默认跟主键做关联
publish = models.ForeignKey(to=Publish) # 不写,默认跟主键做关联
# 自动创建出第三张表(这句话会自动创建第三章表)
# authors在数据库中不存在该字段,没有to_field
# 默认情况:第三张表有id字段,当前Book表的id和Author表的id字段
authors=models.ManyToManyField(to='Author')
class Author(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=32)
age = models.SmallIntegerField()
# 一对一的本质是 ForeignKey+unique
author_detail=models.OneToOneField(to='AuthorDetail',to_field='id')
# author_detail=models.ForeignKey(to='AuthorDetail',to_field='id',unique=True)
class AuthorDetail(models.Model):
id = models.AutoField(primary_key=True)
sex = models.SmallIntegerField()
addr = models.CharField(max_length=64)
phone = models.BigIntegerField()
6 同步到mysql数据库
-配置文件
-pymysql.install_as_mysqldb()
-公司可以用过的mysqlclient
-两条命令
7 2.x版本的django
-外键字段必须加 参数:on_delete
-1.x版本不需要,默认就是级联删除
-假设,
删除出版社,该出版社出版的所有图书也都删除,on_delete=models.CASCADE
删除出版社,该出版社出版的图书不删除,设置为空on_delete=models.SET_NULL,null=True