如何解决Django OneToOneField vs ForeignKey&Unique
我在 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,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?
提前致谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。