python - 从多个 SQLAlchemy 模型创建 Pydantic 模型
问题描述
是否有更好的解决方案将 2+ SQL Alchemy 模型合并为一个 Pydantic 模型?
from typing import List
from pydantic import BaseModel, Any
from sqlalchemy import Column
from sqlalchemy.ext.declarative import DeclarativeMeta, declarative_base
Base: DeclarativeMeta = declarative_base()
class Model1(Base):
__tablename__ = "table1"
id = Column(...)
name = Column(...)
class Model2(Base):
__tablename__ = "table2"
content = Column(...)
class ModelPydantic(BaseModel):
id: Any
name: Any
content: Any
def from_sa_models(self, List[Base]):
# ... merge models here ... ?
pass
class Config:
orm_mode: True
def inside_a_query(...) -> ModelPydantic:
results = await db.execute(...)
(model1, model2) = results.one()
return ModelPydantic(**{**model1.__dict__, **model2.__dict__})
是否可以from_sa_models
使用 SQL Alchemy 基本模型列表创建一个?
解决方案
推荐阅读
- javascript - 通过在反应表单中按 enter 防止用户触发 onSubmit 处理程序
- c# - Swashbuckle.AspNetCore openapi 架构中未正确显示可空属性
- c++ - OpenMP 向量化:如果设置了带有块大小的调度,则 #pragma 向量对齐被忽略?
- sql - SQL请求返回错误的id和错误的结果
- python - 从列表中删除单词,只有第一个 if 语句正在执行
- arrays - 结构数组仅输出 C 中读取的最后一个条目
- google-cloud-platform - 如何查看 Google Cloud Function 实例使用的 IP 地址?
- android - Google play:突出披露中缺少信息
- python - 在 python tkinter 中销毁 GUI 窗口
- javascript - 为什么我用来显示/隐藏 div 的 javascript 在 IE 中不起作用?