models.py

  1. from django.db import models
  2. # Create your models here.
  3. class author(models.Model):
  4. name = models.CharField(max_length=255)
  5. age = models.IntegerField()
  6. # 一对一 默认会和id做集联
  7. # authorDetail表没有数据后会报错
  8. authorDetail = models.OneToOneField(to="authorDetail",on_delete=models.CASCADE) # 与authorDetail表做集联
  9. # authorDetail表没有数据后 authorDetail = null
  10. # authorDetail = models.OneToOneField(to="authorDetail",on_delete=models.SET_NULL) # 不与authorDetail表做集联
  11. class authorDetail(models.Model):
  12. birthday = models.DateField()
  13. telephone = models.CharField(max_length=255)
  14. addr = models.CharField(max_length=255)
  15. # 出版社
  16. class Publish(models.Model):
  17. name = models.CharField(max_length=255)
  18. city = models.CharField(max_length=255)
  19. email = models.EmailField()
  20. # 书籍表
  21. class Books(models.Model):
  22. bid = models.AutoField(primary_key=True)
  23. title = models.CharField(max_length=255)
  24. publisdate = models.DateField()
  25. price = models.DecimalField(max_digits=5,decimal_places=2)
  26. publishs = models.ForeignKey(to="Publish",to_field="id",on_delete=models.CASCADE)
  27. authors = models.ManyToManyField(to="author") # 自动创建第三张表,关联另外两张表的主键字段
  28. # class bookstoauthor(models.Model):
  29. # book_id = models.ForeignKey(to="Books")
  30. # author_id = models.ForeignKey(to="author")

app/init.py

  1. import pymysql
  2. pymysql.install_as_MySQLdb()

数据库生成表

  1. python manage.py makemigrations
  2. python manage.py migrate

会生成5张表

其中 test01_books_authors 表记录了 多对多表的id关联关系
image.png