crodev
crodev

Reputation: 1491

How to make whole row unique in Django

So I have a User model and a Community model. Now in order to check if user has joined a commity I have a UserJoinedCommunity model. It has user and community field. Like so:

class UserJoinedCommunity(models.Model):
    """DB Model for users joined communities"""
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    community = models.ForeignKey(Community, on_delete=models.CASCADE)

    def __str__(self):
        return f"{self.user.username}|{self.community.name}"

So what I want is to make a whole row unique so user can't "join community multiple times". So if users id is 3 and he joins community with id 5 it will created a record ex.{user: 3, community: 5}. I want that to be unique so it can't be created again.

Upvotes: 0

Views: 857

Answers (1)

hanleyhansen
hanleyhansen

Reputation: 6462

What you're looking for is unique_together.

class UserJoinedCommunity(models.Model):
    """DB Model for users joined communities"""
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    community = models.ForeignKey(Community, on_delete=models.CASCADE)

    class Meta:
        unique_together = ['user', 'community']

    def __str__(self):
        return f"{self.user.username}|{self.community.name}"

Note that this will create a constraint in the database. This is not application level constraint. In other words, you'll still have to handle the IntegrityError yourself.

More info here

Upvotes: 1

Related Questions