models.py
from django.db import models# Create your models here.class author(models.Model):name = models.CharField(max_length=255)age = models.IntegerField()# 一对一 默认会和id做集联# authorDetail表没有数据后会报错authorDetail = models.OneToOneField(to="authorDetail",on_delete=models.CASCADE) # 与authorDetail表做集联# authorDetail表没有数据后 authorDetail = null# authorDetail = models.OneToOneField(to="authorDetail",on_delete=models.SET_NULL) # 不与authorDetail表做集联class authorDetail(models.Model):birthday = models.DateField()telephone = models.CharField(max_length=255)addr = models.CharField(max_length=255)# 出版社class Publish(models.Model):name = models.CharField(max_length=255)city = models.CharField(max_length=255)email = models.EmailField()# 书籍表class Books(models.Model):bid = models.AutoField(primary_key=True)title = models.CharField(max_length=255)publisdate = models.DateField()price = models.DecimalField(max_digits=5,decimal_places=2)publishs = models.ForeignKey(to="Publish",to_field="id",on_delete=models.CASCADE)authors = models.ManyToManyField(to="author") # 自动创建第三张表,关联另外两张表的主键字段# class bookstoauthor(models.Model):# book_id = models.ForeignKey(to="Books")# author_id = models.ForeignKey(to="author")
app/init.py
import pymysqlpymysql.install_as_MySQLdb()
数据库生成表
python manage.py makemigrationspython manage.py migrate
会生成5张表
其中 test01_books_authors 表记录了 多对多表的id关联关系
