python - Django Charfield null=未引发 False 完整性错误

标签 python django django-models

我有一个模型:

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 对象时,它不会引发错误。我做错了什么?

> e = Discount()
> e.save()

最佳答案

没有默认的 Django 行为会将 CHARTEXT 类型保存为 Null - 它总是使用空字符串('' )。 null=False 对这些类型的字段没有影响。

blank=False 表示当模型用于呈现 ModelForm 时,默认情况下将需要该字段。它不会阻止您手动保存没有该值的模型实例。

你在这里想要的是一个自定义模型验证器:

from django.core.exceptions import ValidationError
def validate_not_empty(value):
    if value == '':
        raise ValidationError('%(value)s is empty!'), params={'value':value})

然后将验证器添加到您的模型中:

code = models.CharField(max_length=14, unique=True, validators=[validate_not_empty])

这将处理您想要的表单验证,但验证器不会在保存模型实例时自动运行。 Further reading here.如果您想在每次保存实例时验证这一点,我建议覆盖默认的 save 行为,检查那里的字符串值,并在必要时通过引发错误来中断保存。 Good post on overriding save here.

Further reading on null:

Avoid using null on string-based fields such as CharField and TextField. 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. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

And on validators.

关于python - Django Charfield null=未引发 False 完整性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176618/

相关文章:

python - python中的列表识别中的列表

python - 无法为 xml 下载创建 HttpResponse,Django

Django 1.6 按小时和时区过滤问题

python - 如何在 Django 管理页面中添加多个自动完成

Python SFTP : Use SFTP to put memory stream into remote folder. 类似于 FTP storbinary

javascript - Odoo:使用支付收单方添加 Stripe

python - 如何在 django 中为表单创建下拉框?

python - 无法导入 rest_framework_simplejwt

Django 模型 __unicode__ : How to return a value containing localized datetimes?

python - Django:durationField 默认值