I have a model in Django with the following classes (among others):
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'
The trouble comes when I run the server and I find this message (it works but raises a Hint):
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.
The ProjectDiscipline class gathers several disciplines for the same project, and therefore the primary key should be a compound one. I thought this could be done by setting "unique_together" with both "project_name" and "discipline" fields. But it tells me to use the OneToOneField. So... How should it be done? Should I set both fields (project_name and discipline) as OneToOneField linked to the models Project and Discipline respectively, and also keep the unique_together? Or is there a way to avoid using the unique_together?
Thanks in advance.
question from:
https://stackoverflow.com/questions/65937814/django-onetoonefield-vs-foreignkeyunique 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…