将模型的记录配置为唯一的,彼此不重复

时间:2018-07-18 00:52:35

标签: django

我有一个标签模型,该模型与具有多对多关系的文章相关:

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)
    ...

我想确保标签是唯一的并且不是重复的,但是发现很困难

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)...']>

如何将标签的重新编码配置为唯一?

1 个答案:

答案 0 :(得分:1)

可以通过在字段定义中添加unique=True来在field level中指定唯一性,例如:

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

或在model level中使用Meta属性unique_together约束多个字段,例如:

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