在使用SQLModel进行数据库定义的时候,经常需要指定一些表定义的元数据。可以采用如下基础模型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class TableBase(SQLModel, metaclass=DescriptionMeta):
""" 数据库表公共属性模型定义 """
__table_args__ = {
"mysql_engine": "InnoDB", # MySQL引擎
"mysql_charset": "utf8mb4", # 设置表的字符集
"mysql_collate": "utf8mb4_general_ci", # 设置表的校对集
}

# 类名转表名
# https://blog.csdn.net/mouday/article/details/90079956
@declared_attr.directive
def __tablename__(cls) -> str:
snake_case = re.sub(r"(?P<key>[A-Z])", r"_\g<key>", cls.__name__)
return snake_case.lower().strip('_')

这里的 DescriptionMeta 为之前的将 description 属性值转为数据库定义中的 comment。

在定义表的时候,只需要使用如下方式引用即可:

1
2
3
4
5
6
7
8
9
class User(
TimestampModel,
CommonPropertyModel,
UserCreate,
IDModel,
TableBase,
table = True):
""" 展示用户详情信息的用户模型 """
is_active: int = Field(default=0, nullable=True, description="是否激活", sa_type=SmallInteger)

注意一下这里的顺序:TimestampModel, CommonPropertyModel, UserCreate, IDModel,在生成建表语句的时候字段顺序是 IDModel, UserCreate, CommonPropertyModel, TimestampModel