Django models 字段属性
8.6 models 字段属性
- 字符串与数字类型
字段名 | 描述 | 例举 |
---|---|---|
CharField | 字符串类型 | ‘abc’ |
TextField | 文本类型 | ‘abcd…’ |
EmailField | 邮箱类型 | ‘admin@qq.com’ |
UrlField | 网址类型 | ‘http://www.baidu.com’ |
BooleanField | 布尔类型 | True False |
NullBooleanField | 可为空的布尔类型 | None True False |
IntegerField | 整型 | (-2147483648,2147483647) |
SmallIntegerField | 短整型 | (-32768, 32767) |
BigIntegerField | 短整型 | (-∞,+∞) |
PositiveIntegerField | 正整数 | (0, 2147483647) |
PositiveSmallIntegerField | 短正整型 | (0, 32767) |
FloatField | 浮点类型 | 3.14 |
DecimalField | 十进制小数 | 12345.1213123 |
- 时间类型
字段名 | 描述 | 举例 |
---|---|---|
DateField | 日期类型 | xxxx-xx-xx |
TimeField | 时间类型 | xx:xx:xx |
DateTimeField | 日期时间类型 | xxxx-xx-xx xx:xx:xx |
- 文件类型
字段名 | 描述 | 举例 |
---|---|---|
ImageField | 图片类型 | xxx.jpg |
FileField | 文件类型 | 任意文件类型 |
- 特殊类型属性
字段名 | 描述 | 举例 | 作用于 |
---|---|---|---|
max_digits | 数字中允许的最大位数 | 12 | DecimalField |
decimal_places | 储存的十进制位数 | 2 | DecimalField |
width_field | 图片的宽(可以不传) | 1024 | ImageField |
hight_field | 图片高(可以不传) | 576 | ImageField |
upload_to | 保存上传文件的本地路径 | ‘xx/xx.xx’ | FileField ImageField |
- 共有属性
字段名 | 描述 | 举例 | 作用于 |
---|---|---|---|
null | 值是否为空 | True False | |
blank | 值是否为空 | True False | |
parimary_key | 设置主键 | True | 整型 |
auto_now | 时间自动添加 | True | 时间类型 |
auto_now_add | 自动添加时间 仅在创建的时候 | True | 时间类型 |
max_length | 字符串长度 | max_length=20 | 字符串类型 |
default | 默认值 | default=xxx | |
verbose_name | admin 中显示的名字 | verbose_name=name | |
db_colum | 数据库字段名 | db_colum=age | |
unique | 唯一索引 | True | |
db_index | 普通索引 | True |
- 表关联方法
字段名 | 描述 | 必要参数 |
---|---|---|
OneToOneField | 一对一 | (必要参数:on_delete=models.SET_NULL ) |
ForeignKey | 一对多 | (必要参数:on_delete=models.SET_NULL ) |
ManyToManyField | 多对多 |
属性名 | 描述 | 举例 |
---|---|---|
relate_name | 关联表的名字 | relate_name=‘user’ |
on_delete | 外键删除的对策 | on_delete=models.SET_NULL(CASCADE, PROTECT) |