Django OneToOneField vs ForeignKey&Unique

时间:2021-01-28 13:13:37

标签: django model foreign-keys

我在 Django 中有一个模型,其中包含以下类(以及其他类):

class Product(models.Model):
    product = models.CharField(primary_key=True, max_length=50)

    class Meta:
        db_table = 'products'
class Discipline(models.Model):
    discipline = models.CharField(primary_key=True, max_length=100)

    class Meta:
        db_table = 'disciplines'
class Project(models.Model):
    project_name = models.CharField(primary_key=True, max_length=100)
    last_update = models.DateField()
    comments = models.CharField(max_length=150, blank=True, null=True)

    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    main_discipline = models.ForeignKey(Discipline, on_delete=mode
class ProjectDiscipline(models.Model):
    project_name = models.ForeignKey(Project, on_delete=models.CASCADE, db_column='project_name')
    discipline = models.ForeignKey(Discipline, primary_key=True, on_delete=models.CASCADE, db_column='discipline')

    class Meta:
        db_table = 'projects_disciplines'
        unique_together = (('project_name', 'discipline'),)
        verbose_name_plural = 'Projects Disciplines'

当我运行服务器并发现此消息时出现问题(它有效但会引发提示):

planning.ProjectDiscipline.discipline: (fields.W342) Setting unique=True on a ForeignKey has the same effect as using a OneToOneField.
        HINT: ForeignKey(unique=True) is usually better served by a OneToOneField.

ProjectDiscipline 类为同一个项目收集了多个学科,因此主键应该是一个复合键。我认为这可以通过使用“project_name”和“discipline”字段设置“unique_together”来完成。但它告诉我使用 OneToOneField。 那么……应该怎么做?我是否应该将两个字段(项目名称和学科)设置为 OneToOneField 分别链接到模型项目和学科,并保持 unique_together?或者有没有办法避免使用unique_together?

提前致谢。

0 个答案:

没有答案