Wizard
Wizard

Reputation: 22103

Configure the records of model as unique not duplicate with each other

I have a tag model which relate to articles with many-to-many relationship:

class Tag(models.Model):
    owner = models.ForeignKey(User,on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    def __str__(self):
        return self.name
    class Meta:
        ordering = ("id",)

class Article(models.Model):
    tags = models.ManyToManyField(Tag, blank=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    ...

I want to make sure the tags are unique and not duplicate,but found it's difficult

In [39]: article.tags.create(name="django", owner=article.owner)
Out[39]: <Tag: django>
In [40]: article.tags.create(name="django", owner=article.owner)
Out[40]: <Tag: django>
In [41]: article.tags.create(name="django", owner=article.owner)
Out[41]: <Tag: django>
In [42]: article.tags.all()
Out[42]: <QuerySet [<Tag: django>, <Tag: django>, <Tag: django>, <Tag: django>, <Tag: django>]>
In [43]: Tag.objects.all()
Out[43]: <QuerySet [<Tag: django>, <Tag: django>, <Tag: django>, <Tag: django>, <Tag: django>, '...(remaining elements truncated)...']>

How to configure the recodes of Tag as unique?

Upvotes: 0

Views: 26

Answers (1)

RishiG
RishiG

Reputation: 2830

Uniqueness can be specified at the field level by adding unique=True to your field definition, e.g.:

name = models.CharField(max_length=50, unique=True)

or at the model level using the Meta attribute unique_together for constraints on multiple fields, e.g.:

class Meta:
    ordering = ("id",)
    unique_together = ("name", "owner")

Upvotes: 1

Related Questions