一种方法是在 mixin__table_cls__
中Base
或作为 mixin 定义一个类方法。请注意,我没有用任何继承测试过这个。一个例子,如果扩充Base
:
# Python 3.7.2, SQLAlchemy 1.3.13
###
# app/models.py
from sqlalchemy import Table
from sqlalchemy.ext.declarative import declarative_base
class Base(object):
@classmethod
def __table_cls__(cls, *args, **kwargs):
t = Table(*args, **kwargs)
t.decl_class = cls
return t
Base = declarative_base(cls=Base)
设计一个表格示例:
# app/models.py
class Account(Base): # Note this is the customized Base class
__tablename__ = 'account'
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
account_number = Column(String)
在控制台中测试:
# Python 3.7.2 Console
>>> from app import models as m
>>> account_table = m.Base.metadata.tables['account']
>>> account_table.__class__
<class 'sqlalchemy.sql.schema.Table'>
>>> account_table.decl_class
<class 'app.models.Account'>
作为一个函数:
def get_class_by_table_name(table_name):
tbl = Base.metadata.tables[table_name]
return tbl.decl_class
旁注:由于很多答案都引用Base._decl_class_registry
了 ,因此该declarative_base()
函数还接受class_registry
命名参数的字典。
>>> registered_classes = {}
>>> Base = declarative_base(cls=Base, class_registry=registered_classes)
>>> registered_classes.keys()
dict_keys(['Account', '_sa_module_registry', 'AccountType', ...])