多对多表结构的设计ManyToManyField(不会生成某一列、生成一张表):
示例:
脚本:
from django.db import models
# Create your models here.
class Publisher(models.Model):
name = models.CharField(max_length=32)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=32)
pub = models.ForeignKey(Publisher, on_delete=models.CASCADE, )
# def __str__(self):
# return self.name
"""
on_delete 在2.0版本之后是必填的
on_delete=
models.CASCADE 级联删除
PROTECT 保护
SET(1)
SET_DEFAULT 设置为默认值设置为某一个值
SET_NULL 设置为空
DO_NOTHING 什么都不变
"""
class Author(models.Model):
name = models.CharField(max_length=32)
books = models.ManyToManyField("Book")
效果: