- Django orm帮我们自动创建多对多关系
class Book(models.Model):
name = models.CharFiled(max_length=32)
authors = models.ManyToManyField(to='Author')
class Author(models.Model):
name = models.CharField(max_length=32)
- 纯手动创建第三张表
class Book(models.Model):
name = models.CharFiled(max_length=32)
class Author(models.Model):
name = models.CharField(max_length=32)
class Book2Author(models.Model):
book = models.ForeignKey(to='Book')
auhor = models.ForeignKey(to='Author')
info = models.CharField(max_length=32)
- 第三种半自动创建第三种表(推荐:可扩展性高,并且符合orm查询)
class Book(models.Model):
name = models.CharField(max_length=32)
# 第三种创建表的方式
authors = models.ManyToManyField(to='Author',through='Book2Author',through_fields=('book','author'))
class Author(models.Model):
name = models.CharField(max_length=32)
# book = models.ManyToManyField(to='Book',through='Book2Author',through_fields=('author','book'))
class Book2Author(models.Model):
book = models.ForeignKey(to='Book')
author = models.ForeignKey(to='Author')
info = models.CharField(max_length=32)