Search code examples
pythondjangodjango-modelsforeign-keysunique

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!


Solution

  • 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'),)