Django Model 字段参数完整参考文档

目录

一、通用参数(适用于所有字段)

说明:以下参数可用于所有 Django Model 字段类型
参数名 说明 示例
verbose_name 人类可读的字段名称 verbose_name='用户名'
verbose_name_plural 复数名称(主要用于关系字段) verbose_name_plural='用户'
name 字段名(内部使用,通常不手动设置) name='user_name'
null 数据库层面是否允许 NULL 值 null=True
blank 表单验证层面是否允许为空 blank=True
default 默认值,可以是值或可调用对象 default=''default=dict
editable 是否在 admin 界面中可编辑 editable=False
help_text 字段的帮助文本,显示在表单中 help_text='请输入真实姓名'
db_column 自定义数据库列名 db_column='user_name'
db_index 是否为该字段创建数据库索引 db_index=True
db_tablespace 索引的表空间(用于支持的数据库) db_tablespace='indexes'
primary_key 是否将该字段设为主键 primary_key=True
unique 是否在该字段上创建唯一约束 unique=True
unique_for_date 与日期字段组合唯一 unique_for_date='publish_date'
unique_for_month 与月份字段组合唯一 unique_for_month='publish_date'
unique_for_year 与年份字段组合唯一 unique_for_year='publish_date'
auto_created 是否自动创建(内部使用) auto_created=True
validators 验证器列表 validators=[validate_email]
error_messages 自定义错误消息字典 error_messages={'null': '不能为空'}
choices 选项列表,用于限制字段取值 choices=STATUS_CHOICES

二、CharField 参数

注意:max_length 是必需参数
name = models.CharField(
    max_length=100,           # 必需:最大字符长度
    **通用参数
)
参数名 说明 是否必需
max_length 最大字符长度

三、SlugField 参数

提示:SlugField 继承自 CharField,用于 URL 友好的短标签
slug = models.SlugField(
    max_length=50,            # 必需:最大长度
    allow_unicode=False,      # 是否允许 Unicode 字符
    **通用参数
)
参数名 说明 默认值
max_length 最大字符长度 必需
allow_unicode 是否允许非 ASCII 字符(如中文) False

四、TextField 参数

说明:TextField 没有特有参数,只使用通用参数
description = models.TextField(
    blank=True,               # 允许为空
    default='',               # 默认空字符串
    **通用参数
)

五、EmailField 参数

email = models.EmailField(
    max_length=254,           # 默认最大长度 254
    **通用参数
)
参数名 说明 默认值
max_length 最大字符长度 254

六、URLField 参数

website = models.URLField(
    max_length=200,           # 默认最大长度 200
    **通用参数
)
参数名 说明 默认值
max_length 最大字符长度 200

七、数值字段参数

包含字段:IntegerField, SmallIntegerField, BigIntegerField, PositiveIntegerField, PositiveSmallIntegerField, FloatField
count = models.IntegerField(
    default=0,                # 默认值
    **通用参数
)

rating = models.FloatField(
    default=0.0,
    **通用参数
)

注意:数值字段没有特有参数,只使用通用参数。

八、DecimalField 参数

注意:max_digitsdecimal_places 都是必需参数
price = models.DecimalField(
    max_digits=10,            # 必需:总位数(包括小数位)
    decimal_places=2,         # 必需:小数位数
    **通用参数
)
参数名 说明 是否必需
max_digits 数字总位数(包括小数位)
decimal_places 小数位数

九、BooleanField 参数

is_active = models.BooleanField(
    default=True,             # 默认值
    null=True,                # 允许 NULL(三态布尔)
    **通用参数
)

注意:BooleanField 没有特有参数,但设置 null=True 可实现三态布尔(True/False/None)。

十、日期时间字段参数

包含字段:DateField, DateTimeField, TimeField
created_at = models.DateTimeField(
    auto_now=False,           # 每次保存自动更新为当前时间
    auto_now_add=False,       # 创建时自动设置为当前时间
    **通用参数
)
参数名 说明 注意
auto_now 每次保存时自动更新为当前时间 auto_now_add 互斥
auto_now_add 创建对象时自动设置为当前时间 auto_now 互斥

十一、FileField 参数

注意:upload_to 是必需参数
document = models.FileField(
    upload_to='documents/%Y/%m/',  # 必需:上传路径
    storage=None,                    # 自定义存储后端
    max_length=100,                  # 文件路径最大长度
    **通用参数
)
参数名 说明 是否必需
upload_to 上传路径(字符串或函数)
storage 自定义存储后端实例
max_length 文件路径的最大长度 否(默认 100)

十二、ImageField 参数

依赖:使用 ImageField 需要安装 Pillow 库:pip install Pillow
avatar = models.ImageField(
    upload_to='avatars/',      # 必需:上传路径(继承自 FileField)
    height_field=None,          # 自动填充高度的字段名
    width_field=None,           # 自动填充宽度的字段名
    max_length=100,             # 文件路径最大长度
    **通用参数
)
参数名 说明 继承来源
upload_to 上传路径 FileField
storage 自定义存储后端 FileField
max_length 文件路径最大长度 FileField
height_field 用于存储图片高度的字段名 特有
width_field 用于存储图片宽度的字段名 特有

十三、ForeignKey 参数

注意:toon_delete 是必需参数(Django 2.0+)
author = models.ForeignKey(
    to=Author,                # 必需:关联的模型类
    on_delete=models.CASCADE, # 必需:删除关联对象时的行为
    related_name='books',      # 反向查询名称
    related_query_name='book', # 反向查询过滤名称
    limit_choices_to=None,     # 限制可选对象的条件
    parent_link=False,         # 是否作为继承链接
    to_field=None,             # 关联到目标模型的哪个字段
    db_constraint=True,        # 是否创建数据库外键约束
    swappable=True,            # 是否允许模型交换(用于可交换模型)
    **通用参数
)

必需参数

参数名 说明
to 关联的模型类(可以是模型类、字符串或 'self')
on_delete 关联对象被删除时的行为

可选参数

参数名 说明 默认值
related_name 反向查询的名称 '<model_name>_set'
related_query_name 反向查询过滤的名称 related_name 的值
limit_choices_to 限制 admin 下拉选项的字典或 Q 对象 None
parent_link 用于模型继承,标记是否为父链接 False
to_field 关联到目标模型的哪个字段(默认主键) None
db_constraint 是否在数据库层面创建外键约束 True
swappable 是否允许模型交换(如 User 模型) True

on_delete 选项

选项 说明
CASCADE 级联删除,删除关联对象时也删除当前对象
PROTECT 阻止删除,引发 ProtectedError
SET_NULL 设为 NULL(需要设置 null=True
SET_DEFAULT 设为默认值(需要设置 default
SET(value) 设为指定值或调用可调用对象
DO_NOTHING 什么都不做,可能引发数据库完整性错误
RESTRICT 限制删除(Django 3.1+),类似 PROTECT 但更严格

十四、ManyToManyField 参数

tags = models.ManyToManyField(
    to=Tag,                   # 必需:关联的模型类
    related_name='articles',    # 反向查询名称
    related_query_name='article', # 反向查询过滤名称
    limit_choices_to=None,     # 限制可选对象的条件
    symmetrical=True,          # 自关联时是否对称
    through='ArticleTag',      # 自定义中间模型
    through_fields=None,       # 指定中间模型字段
    db_table=None,             # 自定义中间表名
    swappable=True,            # 是否允许模型交换
    **通用参数
)
参数名 说明 默认值
to 关联的模型类 必需
related_name 反向查询的名称 '<model_name>_set'
related_query_name 反向查询过滤的名称 related_name 的值
limit_choices_to 限制 admin 下拉选项 None
symmetrical 自关联时是否对称(如互相关注) True
through 自定义中间模型(用于添加额外字段) None
through_fields 指定中间模型的两个字段名 None
db_table 自定义中间表名 None
swappable 是否允许模型交换 True

十五、OneToOneField 参数

说明:OneToOneField 继承自 ForeignKey,参数完全相同
profile = models.OneToOneField(
    to=Profile,               # 必需:关联的模型类
    on_delete=models.CASCADE, # 必需:删除行为
    related_name='user',      # 反向查询名称
    related_query_name='user', # 反向查询过滤名称
    limit_choices_to=None,     # 限制可选对象
    parent_link=False,         # 是否作为继承链接
    to_field=None,             # 关联到目标模型的哪个字段
    db_constraint=True,        # 是否创建数据库外键约束
    swappable=True,            # 是否允许模型交换
    **通用参数
)

参数与 ForeignKey 完全一致。

十六、JSONField 参数(Django 3.1+)

版本要求:Django 3.1+ 原生支持 JSONField,所有数据库后端都可用
data = models.JSONField(
    encoder=None,             # 自定义 JSON 编码器
    decoder=None,             # 自定义 JSON 解码器
    **通用参数
)
参数名 说明 默认值
encoder JSON 编码器类 None
decoder JSON 解码器类 None

十七、AutoField / BigAutoField 参数

id = models.AutoField(
    primary_key=True,         # 通常自动设置
    **通用参数
)

注意:AutoField 没有特有参数,通常由 Django 自动创建主键。

十八、综合示例

from django.db import models
from django.core.validators import MinValueValidator

class Product(models.Model):
    # CharField 示例
    name = models.CharField(
        '产品名称',
        max_length=200,
        db_index=True,
        unique=True,
        help_text='请输入产品名称',
        error_messages={
            'unique': '该产品名称已存在',
            'blank': '名称不能为空'
        }
    )
    
    # SlugField 示例
    slug = models.SlugField(
        'URL标识',
        max_length=200,
        unique=True,
        allow_unicode=True
    )
    
    # TextField 示例
    description = models.TextField(
        '产品描述',
        blank=True,
        default=''
    )
    
    # DecimalField 示例
    price = models.DecimalField(
        '价格',
        max_digits=10,
        decimal_places=2,
        default=0.00,
        validators=[MinValueValidator(0)]
    )
    
    # 正整数字段示例
    stock = models.PositiveIntegerField(
        '库存',
        default=0,
        db_index=True
    )
    
    # BooleanField 示例
    is_available = models.BooleanField(
        '是否上架',
        default=True,
        editable=True
    )
    
    # 日期时间字段示例
    created_at = models.DateTimeField(
        '创建时间',
        auto_now_add=True,
        db_index=True
    )
    
    updated_at = models.DateTimeField(
        '更新时间',
        auto_now=True
    )
    
    # ImageField 示例
    image = models.ImageField(
        '产品图片',
        upload_to='products/%Y/%m/',
        blank=True,
        null=True,
        height_field='image_height',
        width_field='image_width'
    )
    
    image_height = models.PositiveIntegerField(null=True, blank=True)
    image_width = models.PositiveIntegerField(null=True, blank=True)
    
    # ForeignKey 示例
    category = models.ForeignKey(
        'Category',
        on_delete=models.SET_NULL,
        null=True,
        related_name='products',
        related_query_name='product',
        limit_choices_to={'is_active': True},
        verbose_name='分类'
    )
    
    # ManyToManyField 示例
    tags = models.ManyToManyField(
        'Tag',
        blank=True,
        related_name='products',
        through='ProductTag',
        db_table='product_tags_relation'
    )
    
    # OneToOneField 示例
    supplier = models.OneToOneField(
        'Supplier',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='exclusive_product'
    )
    
    # JSONField 示例
    metadata = models.JSONField(
        '元数据',
        default=dict,
        blank=True
    )
    
    class Meta:
        db_table = 'products'
        ordering = ['-created_at']
        verbose_name = '产品'
        verbose_name_plural = '产品管理'
        unique_together = [['name', 'category']]
        index_together = [['category', 'is_available']]
    
    def __str__(self):
        return self.name

重要提示