首页 > 解决方案 > 在 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 但它没有用

标签: djangodjango-rest-framework

解决方案


就数据库而言,它只允许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']

推荐阅读