'How to have multiple one to one relations to a specific model

I have a scientific info model that has a one-to-one relationship to my User model. this is my model:

class ScientificInfo(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    **other fields**

I want to add an interviewer field to it as well so that I can chose an interviewer from the user model so I added it like this:

class ScientificInfo(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user')
    interviewer = models.OneToOneField(User, on_delete=models.CASCADE, related_name='interviews')
    **other fields**

but when I want to create a new user it gives me unique constraint failed error



Solution 1:[1]

You don't have to use OneToOneField because you're using two relations with the same table. You'd better use ForeignKey.

class ScientificInfo(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='users')
    interviewer = models.ForeignKey(User, on_delete=models.CASCADE, related_name='interviews')
    **other fields**

Hope it could help.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Lu