FastapiAdmin代码生成实战

0 阅读1分钟

1. 新建 model.py 文件

在插件的 model_quant 目录下新建一个 exchange 包,并在包内创建 model.py 文件,内容如下:

#!/usr/bin/env python
# encoding: utf-8
# @version: v1.0
# @author:  Kandy.Ye
# @contact: Kandy.Ye@outlook.com
# @file:    model.py
# @time:    2026/08/24 14:16

from sqlalchemy import Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column

from app.core.base_model import ModelMixin, UserMixin

class QuantExchangeModel(ModelMixin, UserMixin):
    """交易所表
    """

    __tablename__: str = "quant_exchange"
    __table_args__: dict[str, str] = {"comment": "交易所表"}

    name: Mapped[str] = mapped_column(String(50), unique=True, nullable=False, comment='名称', index=True)
    label: Mapped[str] = mapped_column(String(50), nullable=False, comment='显示名称')
    url: Mapped[str | None] = mapped_column(String(255), nullable=True, comment='官网')
    logo_url: Mapped[str | None] = mapped_column(String(255), nullable=True, comment='Logo')
    status: Mapped[int] = mapped_column(Integer, default=0, nullable=False, comment="状态(0:启动 1:停用)", index=True)
    description: Mapped[str | None] = mapped_column(Text, default=None, nullable=True, comment="备注")

2. 生成数据库表

运行下面的命令生成迁移文件:

python main.py revision --env=dev

image.png

接着运行下面的命令应用迁移:

python main.py upgrade --env=dev

image.png

迁移完成后,数据库中就会生成 quant_exchange 表。

image.png

3. 导入数据库表

启动系统后端和前端,进入代码生成页面。

image.png

点击「导入」按钮,在弹出的数据库表列表中选择 quant_exchange 表,然后点击「确定」。

image.png

在导入列表的操作区点击「代码生成」按钮。

image.png

先按图示完成基础配置:

image.png

再进行字段配置:

image.png

接下来预览生成的代码:

image.png

点击「写入本地」按钮后,代码会直接写入对应的目录(目录不存在时会自动创建),并写入数据库的目录表中,后端会自动重启。

系统重启后,刷新缓存即可在菜单中看到「交易所」菜单:

image.png