Django 多对多表的三种创建方式
第一种:
class Book(models.Model): name = models.CharField(max_length=32) # 第一种自动创建 authors = models.ManyToManyField(to='Author') class Author(models.Model): name = models.CharField(max_length=32)
第二种:
class Book2(models.Model): name = models.CharField(max_length=32) class Author2(models.Model): name = models.CharField(max_length=32) # 手动创建第三张表 class Book2Author(models.Model): book = models.ForeignKey(to='Book2') author = models.ForeignKey(to='Author2')
第二种方法好处是可以添加字段,缺点是ORM不可以使用了
第三种方式:
class Book3(models.Model): name = models.CharField(max_length=32) author = models.ManyToManyField(to='Author3',through='Book3Author',through_fields=('book','author')) class Author3(models.Model): name = models.CharField(max_length=32) class Book3Author(models.Model): book = models.ForeignKey(to='Book3') author = models.ForeignKey(to='Author3') info = models.CharField(max_length=32)
可扩展性高,并且能够支持orm 的查询