Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 264
Tortoise1990 Avatar asked Dec 20 '25 12:12

Tortoise1990


1 Answers

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'),)
like image 140
iri Avatar answered Dec 22 '25 05:12

iri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!