如何为SQLAlchemy Base类扩展通用df()类方法
问题描述
我有多个类似下面的SQLAlchemy模型类:
class Weather(Base): __tablename__ = "Weather" id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) temperature = Column(Integer) humidity = Column(Integer) wind_speed = Column(Float) wind_direction = Column(String)
我想给这些类都添加一个df()方法,用来返回对应表的Pandas DataFrame。我知道可以像下面这样单独给每个类实现:
class Weather(Base): __tablename__ = "Weather" id = Column(Integer, primary_key=True, nullable=False, autoincrement=True) temperature = Column(Integer) humidity = Column(Integer) wind_speed = Column(Float) wind_direction = Column(String) @staticmethod def df(): with engine.connect() as conn: return pd.read_sql_table(Weather.__tablename__ , conn)
但我希望所有表类都能复用这个方法,所以尝试扩展Base类来一次性实现,却遇到了无法访问__tablename__属性的问题。
解决方案
我结合了两位开发者的方案——采用无需修改现有代码的实现方式,搭配@classmethod(这正是我之前缺失的部分),最终实现如下:
class MyBase: __tablename__ = None @classmethod def df(cls): with engine.connect() as conn: return pd.read_sql_table(cls.__tablename__ , conn) Base = declarative_base(cls=MyBase)
内容的提问来源于stack exchange,提问作者edoelas
相关产品推荐
相关产品推荐

