sqlite tortoise crud
from enum import IntEnum
from tortoise import connections, fields, models
from tortoise.expressions import F, Q, RawSQL, Subquery
from tortoise.functions import Avg, Sum
class AbstractModel(models.Model):
# 主键,当表里所有属性都没设置pk时,默认生成一个IntField类型 id 的主键
id = fields.UUIDField(pk=True)
class Meta:
# 抽象模型,不生成表
abstract = True
class MixinTimeFiled:
# 添加数据时间 null = True tianjia gengxing buyong fuzhi
created = fields.DatetimeField(null=True, auto_now_add=True)
# 修改数据时间
modified = fields.DatetimeField(null=True, auto_now=True)
class Gender(IntEnum):
MAN = 0
WOMAN = 1
class UserModel(AbstractModel, MixinTimeFiled):
# unique 是否唯一 max—length 数据长度 index 是否索引
username = fields.CharField(
max_length=20, description="描述", unique=True, index=True
)
# null 是否可以为空
nickname = fields.CharField(
max_length=30, description="nickname", null=True, default="777"
)
# description 字段备注 ddl展示, 此处入库的为 0 or 1
gender = fields.IntEnumField(Gender, description="sex", default=Gender.WOMAN)
# max——digits 小输点左边最大位数,decimal——places 小数点右边最大位数99.99
balance = fields.DecimalField(max_digits=2, decimal_places=2, description="balance")
is_admin = fields.BooleanField(default=False)
job_info = fields.JSONField(default=dict) # {}
class Meta:
# 自定义表名,不配置按照类名小写生成 usermodel
table = "tableName"
table_description = "set table ddl desc"
# 多列设置唯一复合所有
# unique_together = (("gender", "balance"),)
# 排序
ordering = ("is_admin",)
# 索引
indexes = ("balance",)
def __str__(self):
return self.username
async def cud():
"""增删改"""
# 新增 返回 一个 UserModel null default ziduan weiyi
# await UserModel.create(username="888", balance=22.135)
# 更新 - 返回改动行数 filter tiaojian k
await UserModel.filter(username="888").update(gender=Gender.MAN) # 0
# await UserModel.filter(username="888").update(gender=0)
# 删除 - 返回改动行数
# await UserModel.filter(username="888").delete()
# 批量创建 - [UserModel,]
# await UserModel.bulk_create(
# [UserModel(username=f"{i}", balance=i) for i in range(2)]
# )
# 批量更新
# users = await UserModel.all()
# for user in users:
# user.gender = 0
# await UserModel.bulk_update(users, fields=["gender"])
async def init():
# Here we create a SQLite DB using file "db.sqlite3"
# also specify the app name of "models"
# which contain models from "app.models"
await Tortoise.init(
# 数据库连接
db_url="sqlite://basic.sqlite3",
# 连接mysql pip install aiomysql
# db_url='mysql://root:[email protected]:3306/tortoise',
# 指定管理的models,__main__ ️当前文件的models.Model
modules={"models": ["__main__"]},
)
# Generate the schema
await Tortoise.generate_schemas()
await cud()
if __name__ == "__main__":
from tortoise import Tortoise, run_async
from logger import logger_db_client
run_async(init())
标签:__,tortoise,fields,await,crud,UserModel,True,sqllite
From: https://www.cnblogs.com/zhuoss/p/17110833.html