🧩 一、让字段可以为空
在 Django 的 models.py
中,可以通过设置字段的两个参数来控制是否允许为空:
参数 | 作用范围 | 说明 |
---|
null=True | 数据库层面 | 数据库字段允许保存 NULL 值 |
blank=True | 表单验证层面 | 表单提交时允许为空(不强制校验) |
✅ 示例:允许字段为空
class User(models.Model):nickname = models.CharField(max_length=50, null=True, blank=True)
null=True
→ 在数据库中该字段可以为 NULLblank=True
→ 在 Django 表单(包括 admin)中该字段可以留空
📘 说明:
- 字符串字段(CharField、TextField) 通常推荐:
blank=True, null=False
(即空字符串 ""
代替 NULL
) - 数字、日期等字段 一般用
null=True
表示无值。
⚙️ 二、Django Model 字段可配置项全集(通用参数)
每个 Django 字段(例如 CharField
, IntegerField
等)都继承自 Field
基类,大多支持以下配置:
参数名 | 类型 | 默认值 | 说明 |
---|
null | bool | False | 数据库是否允许为 NULL |
blank | bool | False | 表单/验证是否允许为空 |
default | any | None | 字段默认值 |
primary_key | bool | False | 是否为主键(会自动加索引) |
unique | bool | False | 是否唯一 |
db_index | bool | False | 是否建立数据库索引 |
db_column | str | None | 指定数据库中的字段名 |
db_tablespace | str | None | 指定索引表空间(较少用) |
choices | iterable | None | 下拉选择的固定值(用于表单) |
verbose_name | str | None | 字段的人类可读名称 |
help_text | str | “” | 帮助提示信息(Admin 显示) |
editable | bool | True | 是否可在表单或 Admin 中编辑 |
error_messages | dict | None | 自定义验证错误提示 |
validators | list | [] | 自定义验证器函数列表 |
auto_created | bool | False | 系统内部标识(通常不手动设) |
unique_for_date | str | None | 限制同一天内唯一(针对日期字段) |
unique_for_month | str | None | 限制同月内唯一 |
unique_for_year | str | None | 限制同年内唯一 |
📘 三、特定字段的额外参数
1️⃣ CharField
参数 | 说明 |
---|
max_length | 字符串最大长度(必须) |
2️⃣ TextField
无额外参数(适合大文本)
3️⃣ IntegerField
/ FloatField
/ DecimalField
参数 | 说明 |
---|
max_digits | 总位数(仅 DecimalField ) |
decimal_places | 小数位数(仅 DecimalField ) |
4️⃣ DateTimeField
/ DateField
参数 | 说明 |
---|
auto_now | 每次保存对象时自动更新为当前时间 |
auto_now_add | 仅在第一次创建时设置时间 |
5️⃣ BooleanField
参数 | 说明 |
---|
默认不允许 NULL,如需三态逻辑用 NullBooleanField (Django 4.0 后用 BooleanField(null=True) 代替) | |
6️⃣ ForeignKey
参数 | 说明 |
---|
to | 关联的模型类 |
on_delete | 删除级联方式(必填,如 models.CASCADE ) |
related_name | 反向引用名 |
related_query_name | 反向查询前缀 |
limit_choices_to | 限制可选关联对象 |
db_constraint | 是否创建外键约束(默认 True) |
7️⃣ ManyToManyField
参数 | 说明 |
---|
to | 关联模型 |
related_name | 反向引用名 |
through | 自定义中间表 |
through_fields | 指定中间表关联字段 |
symmetrical | 是否对称关系(默认 True) |
8️⃣ FileField
/ ImageField
参数 | 说明 |
---|
upload_to | 上传文件的路径或函数 |
storage | 自定义存储系统(如 S3) |
🧠 四、实际开发推荐配置示例
class Product(models.Model):name = models.CharField("产品名称", max_length=100, unique=True)description = models.TextField("描述", blank=True)price = models.DecimalField("价格", max_digits=10, decimal_places=2)stock = models.IntegerField("库存", default=0)category = models.ForeignKey("Category",on_delete=models.SET_NULL,null=True,blank=True,related_name="products")created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)
📚 五、小结
想要的效果 | 设置方法 |
---|
数据库可以为 NULL | null=True |
表单可以留空 | blank=True |
两者都允许 | null=True, blank=True |
仅表单可空,数据库为非空字符串 | blank=True, null=False |