tortoise orm的常用方法及示例

模型

  • 导入依赖
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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值