模型
- 导入依赖
from tortoise.models import Model
- 描述模型
模型示例:
class Tournament(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField(description="名称",min_length=2,max_length=50)
created = fields.DatetimeField(auto_now_add=True)
def __str__(self):
return self.name
class Event(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField(null=True,index=True)
tournament = fields.ForeignKeyField('models.Tournament', related_name='events')
participants = fields.ManyToManyField('models.Team', related_name='events', through='event_team')
modified = fields.DatetimeField(auto_now=True)
prize = fields.DecimalField(max_digits=10, decimal_places=2, null=True)
def __str__(self):
return self.name
class Team(Model):
id = fields.IntField(primary_key=True)
name = fields.TextField()
code = fields.CharField(null=False, max_length=64, default="", description="编码")
def __str__(self):
return self.name
模型 字段内常用标签方法说明:
primary_key
:设置为主键 也可以写为 pk=True
,默认是False。
null
:是否允许字段为空,null=True
表示允许为空,程序默认是null=False
,即不许为空。
default
:设置默认值。
unique
:设置是否为唯一字段,unique=True
表示该字段在表中唯一,默认是False。
index
:设置索引。index=True
表示设置该字段为索引,默认是False。
description
:设置字段描述内容。
max_length
:接收最长长度。
min_length
:接收最短长度。
max_digits
:针对DecimalField
,该字段允许的最大位数(包括整数部分和小数部分的所有数字)。
decimal_places
:针对DecimalField
,指定该字段的小数位数。
choices
:设置预选字段,示例如下:
STATUS_CHOICES = [("active", "Active"), ("inactive", "Inactive")]
status = fields.CharField(max_length=10, choices=STATUS_CHOICES)
auto_now_add=True
:仅在创建时自动设置当前时间,之后不可更改,即在调用.create方法或保存新实例的时候,自动设置当前时间。
auto_now=True
:每次保存(创建或更新)时都自动设置当前时间。
__str__(self)
方法:定义当对象被转换为字符串时应该返回什么内容.
-
Meta 方法
Meta用于定义模型的元数据
class Foo(Model):
...
class Meta:
table="custom_table"
unique_together=(("field_a", "field_b"), )
indexes = [("name", "team")] # 创建 (name, team) 组合索引
db_table_prefix