Exclude used items in a one to many relationship

Viewed 16

I'm trying to realize this relationship:

-A user can have multiple social networks, but each social ONLY ONCE

-A social network can have multiple users.

I need to avoid a user choose more than one time the same social.

Is somethig that has to be done in the model, or later filtering a user choice

class Social(models.Model):
    name = models.CharField(max_length=200)
    link = models.CharField(max_length=200)
    def __str__(self):
        return self.name

class Social2User(models.Model):
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
    social = models.ForeignKey(Social, null=True, on_delete=models.CASCADE)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['user', 'social'], name='unique_migration_host_combination'
            )
        ]
    
    def __str__(self):
        return self.user.username + '-' + self.social.name

class UserInfos(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    bio = models.TextField(null=False)
    def __str__(self):
        return self.user.username

Thank you

0 Answers
Related