问题描述
我有一个模型:
class Discount(models.Model):
code = models.CharField(max_length=14, unique=True, null=False, blank=False)
email = models.EmailField(unique=True)
discount = models.IntegerField(default=10)
在我的shell中,当我尝试保存没有输入的Discount对象时,它不会引发错误。我在做什么错了?
In my shell when I try and save a Discount object with no input, it doesn't raise an error. What am I doing wrong?
> e = Discount()
> e.save()
推荐答案
没有默认的Django行为会保存 CHAR
或 TEXT
类型为 Null
-它将始终使用一个空字符串(''
)。 null = False
对这些类型的字段没有影响。
No default Django behavior will save CHAR
or TEXT
types as Null
- it will always use an empty string (''
). null=False
has no effect on these types of fields.
blank = False
表示在使用模型渲染ModelForm时,默认情况下该字段是必需的。它不会阻止您手动保存不带该值的模型实例。
blank=False
means that the field will be required by default when the model is used to render a ModelForm. It does not prevent you from manually saving a model instance without that value.
这里想要的是自定义模型验证器:
What you want here is a custom model validator:
from django.core.exceptions import ValidationError
def validate_not_empty(value):
if value == '':
raise ValidationError('%(value)s is empty!'), params={'value':value})
然后将验证器添加到模型中:
Then add the validator to your model:
code = models.CharField(max_length=14, unique=True, validators=[validate_not_empty])
这将处理您想要的表单验证,但是验证器不会自动运行保存模型实例时。 每次保存实例时都要对此进行验证,我建议重写默认的 save
行为,在其中检查字符串的值,并在必要时通过引发错误来中断保存。
This will take care of the form validation you want, but validators don't automatically run when a model instance is saved. Further reading here. If you want to validate this every time an instance is saved, I suggest overriding the default save
behavior, checking the value of your string there, and interrupting the save by raising an error if necessary. Good post on overriding save
here.
这篇关于Django Charfield null = False不引发完整性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!