Model Class & Database
Model 类 与 数据库 的对应关系Model 结构
- 只有 Fields 是必须要的
from django.db import models
class Person(models.Model):
# Fields
first_name = models.CharField(max_length=64)
last_name = models.CharField(max_length=64)
age = models.IntegerField()
# MetaData
class Meta:
ordering = ["-age"]
verbose_name_plural = "people"
# Model methods
@property
def full_name(self):
"Returns the person's full name."
return '%s %s' % (self.first_name, self.last_name)
def __str__(self):
return self.full_name()
# Override predefined model methods
def save(self, *args, **kwargs):
do_something()
super().save(*args, **kwargs) # Call the "real" save() method.
do_something_else()
Fields
FieldsField Types
Field Options
项的选项分为:
# 公共选项
CHOICES = [
('store value', 'display value')
]
# 选项 = 默认值
null = False
blank = False
default =
help_text =
primary =
unique =
verbose_name = # 也是第一个位置参数
choices = CHOICES # display value : .get_<field_name>_display()
Metadata
# metadata 用于定义关于整个表的附加信息
ordering # 排序依据
db_table # 表名
verbose_name # 用于显示的 单数名称
verbose_name_plural # 用于显示的 复数名称,默认是直接 +s
Model Methods
定义一个作用于数据库中的一行(record)的函数
通常需要定义:def __str__(self)
可能需要重载预定义的方法:save()
, delete()
Using Models
# project/settings.py
INSTALLED_APP = [
# ....
'myapp',
# ....
]
$ python manage.py makemigrations myapp
$ python manage.py migrate
网友评论