1

I have a Tag model, that must have a name field that needs to be unique, but only for that user's tags.

So that one user can't create two 'tagname' tags, but many different users can (create a tag with the same name).

The field must be unique inside the models that relate to the User.

This is the Model.

class User(AbstractUser):
      email = models.EmailField(unique=True)

class Tag(models.Model):
      name = models.CharField(max_length=30, unique=True)
      user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, 
             related_name='tags')

1 Answers1

0

If you are using Django 2.1 or older you can use unique_together like this:

class Tag(models.Model):
    name = models.CharField(max_length=30, unique=True) 
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='tags')

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

If you are using Django 2.2 you can use UniqueConstraint instead of unique_together like this:

class Tag(models.Model):
    name = models.CharField(max_length=30, unique=True) 
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='tags')

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['name', 'user'], name='give_it_some_name')
    ]

As the docs state:

Use UniqueConstraint with the constraints option instead.

UniqueConstraint provides more functionality than unique_together. unique_together may be deprecated in the future.

Community
  • 1
  • 1
Stevy
  • 3,228
  • 7
  • 22
  • 38