- 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.CharField(max_length=32) class Author(models.Model): name = models.CharFiled(max_length=32) class Book2Author(models.Model): book = models.ForeignKey(to="Book") Author = models.ForeignKey(to="Author") info = models.CharFiled(max_length=32)
手动创建第三张表,并通过字段进行关联(可扩展性搞,支持直接跨表查询)
class Book(models.Model): name = models.CharFiled(max_length=32) authors = models.ManyToManyField(to="Author", through="Book2Author", through_fields=("book", "author")) class Author(models.Model): name = models.CharFiled(max_length=32) #books = models.Many2ManyField(to="Book", through="Book2Author", through_fields=("author", "book")) # 与book表中的最后一个字段二选一 class Book2Author(models.Model): book = models.ForeignKey(to="Book") Author = models.ForeignKey(to="Author") info = models.CharField(max_length=32)