Model validation on update in django

孤者浪人 提交于 2019-12-22 10:53:22

问题


I've created a model called Term and a validator for it, like this:

from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError


def validate_insensitive_exist(value):
            exists = Term.objects.filter(word__iexact = value.lower()).exists()
            if exists == True:
                    raise ValidationError("This term already exist.")


class Term(models.Model):
        word = models.CharField(max_length=200, unique=True, validators=[validate_insensitive_exist])
        related_term = models.ManyToManyField("self", null=True, blank=True)
        def __unicode__(self):
                return self.word
        def natural_key(self):
                return self.word

What this validator does is to raise an exception when I try to add a term that already exists (in lower or uppercase), and it's working fine. My problem is that when I try to edit an existing term (just to put a character in upper or lowercase - but the word is the same), an exception is raised because in fact i'm trying to add a word that already exists, being itself. What I want is to validate the new word that I enter against all the other terms, ignoring the word that was in the first place and that I'm actually changing.

Can anyone help me with that?


回答1:


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


来源:https://stackoverflow.com/questions/28966330/model-validation-on-update-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!