django - 在 Django 中将模型字段设置为必填
问题描述
Django 在模型/数据库级别不强制执行 NOT NULL。device_serial 既不应该有空白 '' 也不应该为空
class Device(models.Model):
device_serial = models.CharField(max_length=36, unique=True, null=False, blank=False)
....etc
下面的语句完全正常!我预计它会失败,因为 device_serial 是必需的。它不应该接受空字符串 ''
Device.objects.create(device_serial='')
如何在模型/数据库级别创建必填字段?我可能在这里做错了什么?我不明白我哪里出错了。我试过 ''.strp() 将空字符串转换为 None 但它没有用
解决方案
就数据库而言,它只允许null/not null由处理null=True/False
并默认为False
. blank=True/False
仅用于管理页面。
该字符串''
不被视为空,这就是当您有null=False
约束时它被数据库接受的原因。
如果您想避免数据库级别的空白字符串,您可以覆盖save()
模型本身并在设置为空字符串时引发异常device_serial
,例如:
from django.core.exceptions import ValidationError
class Device(models.Model):
device_serial = models.CharField(max_length=36, unique=True)
def save(self, *args, **kwargs):
if self.device_serial == '':
raise ValidationError('device_serial cannot be empty')
super().save(*args, **kwargs)
现在,当您尝试使用空字符串(调用save()
)创建对象时,将引发以下异常:
django.core.exceptions.ValidationError: ['device_serial cannot be empty']
推荐阅读
- amazon-web-services - 由于 KMS 权限,SageMaker Studio 域创建失败
- c - 只是想知道用 C 编写的这段代码是如何工作的
- spring - 查询方法公共抽象 org.springframework.data.domain.Page 的验证失败
- tesseract - Tesseract 4.1.1 与 Tika 1.26 的兼容性
- .net - 使用 IdentityServer 在 .NET API 上找不到控制器路由
- python - 我们如何在热图中绘制来自多索引数据框的数据?
- python - 有人可以解释以下pytorch神经网络中的层代码吗
- python - Python on write time 在 vscode 中显示来自 dict 的建议/提示
- jenkins - 将 jenkins 与 GoCD 集成
- javascript - 如何优化 useReducer 中对象数组的更新?