django设置多对多关系的三种方法,如果对第三张表有增加字段的需求,可考虑后两种。
django帮我们生成第三张表
class Author(models.Model):
name = models.CharField(max_length=32)
books = models.ManyToManyField(\'Book\') # 不在Author表中生产字段,生产第三张表
自己创建第三张表
class AuthorBook(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
date = models.DateField()
自建的表和 ManyToManyField 联合使用
使用参数through:将自建的表设置成ManyToManyField的第三张表
class Author(models.Model):
name = models.CharField(max_length=32)
books = models.ManyToManyField(\'Book\',through=\'AuthorBook\')
class AuthorBook(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
date = models.DateField()
特殊:自建表中有对同一个表多个外键的情况
使用参数through_fields:指定外键名,说明第三张表中只有这些外键
class Author(models.Model):
name = models.CharField(max_length=32)
books = models.ManyToManyField(\'Book\',through=\'AuthorBook\',through_fields=[\'author\',\'book\']
class AuthorBook(models.Model):
author = models.ForeignKey(Author,related_name=\'a\' ,on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
tuijian = models.ForeignKey(Author,related_name=\'b\',on_delete=models.CASCADE)
参数related_name:用来区分同一个表的外键,方便之后用来反向查询