Django Model中字段(Field)的选项

CharField() 字符字段
必选项:max_length = xxx or None
如不是必填项,可设置blank = True和default = ''
如果用于username, 想使其唯一,可以设置unique = True
如果有choice选项,可以设置 choices = XXX_CHOICES

TextField() 文本字段
max_length = xxx
如不是必填项,可设置blank = True和default = ''

DateField() and DateTimeField() 日期与时间字段
一般建议设置默认日期default date.
For DateField: default=date.today - 先要from datetime import date
For DateTimeField: default=timezone.now - 先要from django.utils import timezone
对于上一次修改日期(last_modified date),可以设置: auto_now=True

EmailField() 邮件字段
如不是必填项,可设置blank = True和default = ''
一般Email用于用户名应该是唯一的,建议设置unique = True

IntegerField(), SlugField(), URLField(),BooleanField()
可以设置blank = True or null = True
对于BooleanField一般建议设置defautl = True or False

FileField(upload_to=None, max_length=100) - 文件字段
必须项:upload_to = "/some folder/"
max_length = xxxx

ImageField(upload_to=None, height_field=None, width_field=None, max_length=100,)
必须项:upload_to = "/some folder/"
其他选项是可选的.

ForeignKey(to, on_delete, **options) - 单对多关系
to必需指向其他模型,比如 Book or 'self' .
必需指定on_delete options(删除选项): i.e, "on_delete = models.CASCADE" or "on_delete = models.SET_NULL" .
可以设置"default = xxx" or "null = True" .
如果有必要,可以设置 "limit_choices_to = ",如下面例子。
staff_member = models.ForeignKey( User, on_delete=models.CASCADE, limit_choices_to={'is_staff': True}, )
可以设置 "related_name = xxx" 便于反向查询。

ManyToManyField(to, **options) - 多对多关系
to 必需指向其他模型,比如 User or 'self' .
设置 "symmetrical = False " if 多对多关系不是对称的
设置 "through = 'intermediary model' " 如果需要建立中间模型来搜集更多信息
可以设置 "related_name = xxx" 便于反向查询。

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值