Django Charfield null = False不引发完整性错误 [英] Django Charfield null=False Integrity Error not raised
问题描述
我有一个模型:
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.
避免在基于字符串的字符串上使用null字段(例如CharField和TextField),因为空字符串值将始终存储为空字符串,而不是NULL。如果基于字符串的字段具有null = True,则意味着它具有无数据的两个可能值:NULL和空字符串。在大多数情况下,为无数据设置两个可能的值是多余的; Django惯例是使用空字符串,而不是NULL。
Avoid using null on string-based fields such as CharField and TextField because empty string values will always be stored as empty strings, not as NULL. If a string-based field has null=True, that means it has two possible values for "no data": NULL, and the empty string. In most cases, it’s redundant to have two possible values for "no data;" the Django convention is to use the empty string, not NULL.
这篇关于Django Charfield null = False不引发完整性错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!