Model validation on update in django

折月煮酒 提交于 2019-12-05 19:32:21
Alasdair

You can't use a validator for this, because a validator only has access to the value, not to the model instance that you are trying to validate.

You can define a clean method for your model, and exclude the current instance from the queryset.

class Term(models.Model):
    word = models.CharField(max_length=200, unique=True)
    related_term = models.ManyToManyField("self", null=True, blank=True)


    def clean(self):
        other_terms = Term.objects.filter(word__iexact=self.word.lower())
        if self.pk:
            other_terms = other_terms.exclude(pk=self.pk)
        if other_terms.exists():
            raise ValidationError("This term already exists.")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!