Home > Software engineering >  How to restrict a Django model to a single one-to-one relation?
How to restrict a Django model to a single one-to-one relation?

Time:10-31

I am currently building a Django app that requires two different user types and I know that storing authentication information across multiple models/tables is a bad idea.

As such, I have created a User model to handle the authentication information (username, password, etc.). I have then created two different models, one for the buyers and one for the sellers, each with their own unique fields and one-to-one relationship to the User model.

Now, I thought this would work, but the problem is that it is still possible for a different buyer and seller to have the same User relation. How can I prevent this and restrict the User model to only a single one-to-one relation?

CodePudding user response:

You can add that field to user model instead of your way, by doing that you can ensure one user can only have one type

CodePudding user response:

You can use unique_together to achieve your goal like this:

class Buyer(models.Model):
    user_id = models.ForeignKey(User, ...)
    id = models.AutoField(primary_key=True)
    
    class Meta:
        unique_together = ('id', 'user_id',)

class Buyer(models.Model):
    user_id = models.ForeignKey(User, ...)
    id = models.AutoField(primary_key=True)
    
    class Meta:
        unique_together = ('id', 'user_id',)

By this way, one Buyer is linked to only one user and one Seller is linked to only one user too.

  • Related