Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

model - Django OneToOneField vs ForeignKey&Unique

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...