Skip to main content
 首页 » 编程设计

python之SQLAlchemy:如何将通用映射逻辑添加到我的自定义基类(使用声明式映射)

2025年05月04日7xing901022

我有一个项目,其中每个表都有一些公共(public)字段,例如状态,我想为所有这些字段起别名。是否可以在不手动为每个类添加别名的情况下执行此操作?例如,这是我现在拥有的:

from core import foo_table, bar_table, Status  
 
Base = declarative_base() 
 
def CustomBase(object): 
   @property 
   def status(self): 
      return Status(self._status) 
  ... 
 
def Foo(Base, CustomBase): 
   __table__ = foo_table 
   _status = foo_table.c.status 
   ... 
 
 
def Bar(Base, CustomBase): 
   __table__ = bar_table 
   _status = bar_table.c.status 
   ... 

理想情况下,我希望能够在 CustomBase 上而不是在 Foo 和 Bar 上设置我的 _status 别名,或者设置我的项目以便在加载扩展 CustomBase 的类时添加别名。这是可能的还是我试图以错误的方式完成这个?我知道如果我重命名我的数据库中的状态字段或重命名 CustomBase 中的状态属性,我可以让它工作,但我宁愿尽可能避免这种情况,因为它们都是同一事物的表示,并且没有必要通过代码直接访问枚举值。

谢谢!

请您参考如下方法:

您最好的选择可能是创建一个自定义的 Column 类型,该类型使 Enum 能够与您自己的 Status 类相互转换。参见 here一个完整的引用。以下是您的核心模块的草稿,具体代码取决于您的情况。

# core module 
 
import sqlalchemy.types as types 
 
class DBStatus (types.TypeDecorator): 
 
    impl = types.Enum 
 
    # what should happen with Status objects on the way into the table 
    def process_bind_param(self, value, dialect): 
        if value is None: 
            return value 
        return str(value)  # if Status has a __str__ or __repr__ method 
 
    # what should happen with Enum objects on the way out of the table 
    def process_result_value(self, value, dialect): 
        if value is None: 
            return value 
        return Status(value) 
 
foo_table = Table( 
    'foo', 
    MetaData(), 
    Column('status', DBStatus('OK', 'Error')), 
    # ... 
) 

在此之后,您不必再在带有映射的模块中做任何特殊的事情:

# module with the mappings 
 
Base = declarative_base() 
 
class Foo (Base): 
    __table__ = foo_table 
    # ... 

事实上,就 Status 列而言,它非常简单,您也可以使用完整的声明式映射。

# everything in one module 
 
class DBStatus (types.TypeDecorator): 
 
    # same as above 
 
Base = declarative_base() 
 
class Foo (Base): 
    status = Column(DBStatus('OK', 'Error')) 
    # ...