Tortoise1990
Tortoise1990

Reputation: 53

Django: Making a value in a model unique specific to a user

I have a model for a project:

class Project(models.Model):
    name = models.CharField(max_length=200, unique=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

I want to make the project name a unique value per user but at the moment if user 1 creates a name of "project 1" then user 2 is unable use that project name.

What is the best way to go about this?

Thanks!

Upvotes: 3

Views: 630

Answers (1)

iri
iri

Reputation: 744

unique_together is probably what you are looking for.

class Project(models.Model):

    name = models.CharField(max_length=200)
    user = models.ForeignKey(User, on_delete=models.CASCADE)

    class Meta:
        unique_together = (('name', 'user'),)

Upvotes: 4

Related Questions