1

Context:

  • I want to build an API using FastAPI and SQLModel
  • I need to use database reflection to create the SQLModel table models based on existing database
  • I couldnt find how to do database reflection directly in SQLModel
  • So I do database reflection in SQLAlchemy and now i want turn the SQLAlchemy table models into SQLModel ones to easily utilize them with FastAPI

Problem:

I cant figure out how to create an SQLModel table model based on the SQLAlchemy table model which i created with database reflection. as shown in the code below. The docs of SQLModel suggest easy integration of SQLAlchemy so i figured it should be easy...

from sqlalchemy import create_engine
from sqlalchemy.orm import  sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base

from fastapi import FastAPI
from sqlmodel import SQLModel

app = FastAPI()

# do database reflection
engine = create_engine('sqlite:///database.db')
Base = declarative_base()
Base.metadata.reflect(engine)

print("alchemy meta tables:\n ", Base.metadata.tables)

# creates SQLAlchemy model based on database table schema of table 'hero'
class HeroDBReflection(Base):
    __table__ = Base.metadata.tables['hero']

# TODO: How to create this Hero SQlModel data model based on the SQLAlchemy model 'HeroDBReflection'?
# class Hero(SQLModel, table=True):
#     metadata = Base.metadata.tables['hero'] ?

# @app.post("/heroes/", response_model=Hero)
# def create_hero(hero: Hero):
#     session.add(hero)
#     session.commit
#     session.refresh(hero)
#     return hero

*This is my first Stackoverflow post, so I hope that my question is clear :)

Thanks a lot!

Toffy_
  • 11
  • 1
  • `SQLModel` is a very new library (only version 0.0.8), so I don't think this functionality has been implemented. – M.O. Oct 11 '22 at 16:46

0 Answers0