首页 > 解决方案 > 从多个 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 基本模型列表创建一个?

标签: pythonsqlalchemypydantic

解决方案


推荐阅读