Django的型号多到许多与桥表

时间:2019-01-30 22:47:18

标签: django python-3.x django-models

我试图了解如何正确设置我的模型以建立多对多关系,我注意到创建模型时有一个ManyToManyField选项,但我似乎无法理解它的逻辑以及如何使其正常工作。我想分享我的代码并进行解释。

from django.db import models

class Major(models.Model):
    name = models.CharField(max_length=30, db_index=True)

class School(models.Model):
    name = models.Charfield(max_length=50, db_index=True)
    majors = models.ManyToManyField(Major)

class Professor(models.Model):
    ProfessorIDS = models.IntegerField()
    ProfessorName = models.CharField(max_length=100)
    ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4)
    NumberOfRatings = models.CharField(max_length=50)
    school = models.ForeignKey(School , on_delete=models.CASCADE)
    major = models.ForeignKey(Major , on_delete=models.CASCADE)

请注意,学校表(班级)具有多对多的专业,这实际上是我想要的,其目标是建立一个数据库,以允许在单个学校下存储多个专业。

经过研究,我得出结论认为这没有道理,创建一个Bridge Table会更好,所以我决定像这样创建我的模型...

from django.db import models

class Major(models.Model):
    name = models.CharField(max_length=30, db_index=True)

class School(models.Model):
    name = models.Charfield(max_length=50, db_index=True)


class School_Majors(models.Model):
    school = models.ForeignKey(School, on_delete=models.CASCADE)
    major = models.ForeignKey(Major, on_delete=models.CASCADE)

class Professor(models.Model):
    ProfessorIDS = models.IntegerField()
    ProfessorName = models.CharField(max_length=100)
    ProfessorRating = models.DecimalField(decimal_places=2,max_digits=4)
    NumberOfRatings = models.CharField(max_length=50)
    school = models.ForeignKey(School , on_delete=models.CASCADE)
    major = models.ForeignKey(Major , on_delete=models.CASCADE)

这不是设置数据库以从学校添加和删除多个专业的更合适的方法吗?

1 个答案:

答案 0 :(得分:2)

  

最好创建一个桥接表

ManyToManyField就是这样做的。您的两个摘要在功能上是相同的。

如果您可能希望在穿透表上有一些额外的数据(在Django世界中被称为),例如第一次提供专业时的现场记录,则可以使用through参数ManyToManyField,如下:

from django.db import models

class Major(models.Model):
    name = models.CharField(max_length=30, db_index=True)


class School(models.Model):
    name = models.CharField(max_length=30, db_index=True)
    majors = models.ManyToManyField(Major, through='SchoolMajor')


class SchoolMajor(models.Model):
    major = models.ForeignKey(Major, on_delete=models.CASCADE)
    school = models.ForeignKey(School, on_delete=models.CASCADE)
    first_offered = models.DateField()

改编自here