Python 如何在django中使用验证器

Python 如何在django中使用验证器,python,sql,django,validation,django-models,Python,Sql,Django,Validation,Django Models,我希望此代码在键入以下内容时引发错误 class Exam(models.Model): #Exam can have many questions subject = models.TextField(primary_key=True, unique = True, validators = [validate_subject]) #make it to reject a string of length 0 def __str__(self): retu

我希望此代码在键入以下内容时引发错误

class Exam(models.Model):  #Exam can have many questions
    subject = models.TextField(primary_key=True, unique = True, validators = [validate_subject])  #make it to reject a string of length 0

    def __str__(self):
        return self.subject
为什么我没有收到错误?

当您
.save()
对象时,验证程序不会运行,这主要是出于性能原因。可以调用来验证模型对象:

from my_app.models import Exam
exam = Exam()
exam.subject = ""
exam.save()
来自my_app.models导入考试
考试
考试科目=“”
考试。全勤
exam.save()
ModelForm
还将清理模型对象,因此如果您通过
ModelForm
创建或更新模型,验证程序将运行

class Exam(models.Model):  #Exam can have many questions
    subject = models.TextField(primary_key=True, unique = True, validators = [validate_subject])  #make it to reject a string of length 0

    def __str__(self):
        return self.subject
from my_app.models import Exam
exam = Exam()
exam.subject = ""
exam.save()
from my_app.models import Exam

exam = Exam()
exam.subject = ''
exam.full_clean()
exam.save()