Django:重写Model.validate_unique

时间:2012-12-28 20:47:59

标签: django django-models

覆盖Django的Model.validate_unique的正确方法是什么?我尝试覆盖它并提升我自己的ValidationError,但是出现了这个错误:

AttributeError: 'ValidationError' object has no attribute 'message_dict'

1 个答案:

答案 0 :(得分:22)

Django希望您的ValidationErrors可以使用字典而不是字符串进行实例化:

from django.db.models import Model
from django.core.exceptions import ValidationError
from django.core.exceptions import NON_FIELD_ERRORS


class Person(Model):

    ...

    def validate_unique(self, *args, **kwargs):
        super(Person, self).validate_unique(*args, **kwargs)
        if not self.id:
            if self.__class__.objects.filter(...).exists():
                raise ValidationError(
                    {
                        NON_FIELD_ERRORS: [
                            'Person with same ... already exists.',
                        ],
                    }
                )