字段与选项(必选项为黄色标注)
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" 便于反向查询。
常见的Django Model META类选项
# models.py
from django.db import models
class Meta:
# 按Priority降序, order_date升序排列.
get_latest_by = ['-priority', 'order_date']
# 自定义数据库里表格的名字
db_table = 'music_album'
# 按什么排序
ordering = ['pub_date']
# 定义APP的标签
app_label = 'myapp'
# 声明此类是否为抽象
abstract = True
# 添加授权
permissions = (("can_deliver_pizzas", "Can deliver pizzas"),)
0
登陆后方可评论