我最近发现了这个问题,因为我偶然发现了同样的问题。
在仔细阅读之后,我想用 SQLAlchemy 提供的这个现代且非常有用的 (IMHO) 解决方案来更新答案 - Automap https://docs.sqlalchemy.org/en/14/orm/extensions/automap.html
更新(由rikyeah 建议):
假设我们想要一个包含俱乐部的表格 - id、名称等。
我们可以这样做:
from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String, SmallInteger, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.automap import automap_base
from settings import load_settings
Base = declarative_base()
# ORM object
class Club(Base):
__tablename__ = "club"
id = Column(Integer, primary_key=True)
native_name = Column(String)
english_name = Column(String)
country_code = Column(String)
country_name = Column(String)
current_league = Column(String)
def __init__(self,
pk, native_name, english_name, country_code, country_name, current_league):
self.id = pk
self.native_name = native_name
self.english_name = english_name
self.country_code = country_code
self.country_name = country_name
self.current_league = current_league
print(f'The type of Club class is {type(Club)}')
控制台:
>>>The type of Club class is <class 'sqlalchemy.orm.decl_api.DeclarativeMeta'>
但是
如果我们的数据库中已经有这个表,我们可以加载它:
# let's try AutoMap!
pg, sa_settings = load_settings()
engine = create_engine(url=sa_settings['sql_uri']);
metadata = MetaData()
metadata.reflect(engine)
Base = automap_base(metadata=metadata)
Base.prepare()
# The magic follows
ClubDB = Base.classes.club
print(f'The type of ClubDB is {type(ClubDB)}')
和控制台输出是同一个类:
>>>The type of ClubDB is <class 'sqlalchemy.orm.decl_api.DeclarativeMeta'>