django外键三种多对多关系表的创建

三种 全自动 半自动 纯手动

全自动

以图书和作者为例

class Book(model.Model):
    title = model.CharField(max_length=32)
    authors = model.ManyToManyField(to='Author')


class Author(model.Model):
    name = model.CharField(max_length=32)
 

纯手动

class Book(model.Model):
    title = model.CharField(max_length = 32)


class Author(model.Model):
    name = model.CharField(max_length = 32)



class Book2Author(model.Model):
    book = model.ForeignKey(to='Book',on_delete=models.CASCADE)
    author = model.ForeignKey(to='Author',on_delete=models.CASCADE)

半自动

class Book(model.Model):
    title = model.CharField(max_length=32)
    author = model.ManyToManyField(to='Author',through='Book2Author',though_fields = ('book','author'))
        


class Author(model.Model):
    name = model.CharField(max_length=32)


class Book2Author(model.Model):
     book = model.ForeignKey(to='Book',on_delete=models.CASCADE)
     author = model.ForeignKey(to='Author',on_delete=models.CASCADE)

半自动相对使用较多 有好的扩展性且可以使用orm查询

建立外键时要添加on_delete参数 1.x版本会默认级联删除,之后的版本都需额外填写否则会报错

 

上一篇:python测试开发django-12.models设置主键primary_key


下一篇:django代码