sqlalchemy orm列名称约定

时间:2018-08-17 00:35:51

标签: python sqlalchemy

如何将表格my_column的所有字段自动映射到数据库中的相应列MyColumn

class MyTable(Base):
    __tablename__ = 'MyTable'
    # what I have now:
    my_column_1 = Column('MyColumn1', Integer)
    # what I want: how to configure a convention mapping rule for this:
    my_column_1 = Column(Integer)

1 个答案:

答案 0 :(得分:0)

您可以提供自己的重命名列的元类,然后再将控制权传递给DeclarativeMeta。另一种选择是在before_parent_attach事件处理程序中更改Column的列名,但是与使用特定声明基的映射类中的列相比,这将全局影响所有列。

from sqlalchemy.ext.declarative.api import DeclarativeMeta
from sqlalchemy import Column

class RenamingDeclarativeMeta(DeclarativeMeta):
    def __init__(cls, name, bases, namespace):
        _rename_declared_columns(namespace)
        super().__init__(name, bases, namespace)

    def __setattr__(cls, key, value):
        if isinstance(value, Column):
            _undefer_column_name_only(key, value)
        super().__setattr__(key, value)

def to_camelcase(s):
    return ''.join([w.title() for w in s.split('_')])

def _undefer_column_name_only(key, column):
    if column.name is None:
        column.name = to_camelcase(key)

def _rename_declared_columns(namespace):
    for key, attr in namespace.items():
        if isinstance(attr, Column):
            _undefer_column_name_only(key, attr)

这省略了一些功能,例如重命名ColumnPropertyCompositeProperty属性中包含的列。为了使用它,请将其作为metaclass传递到declarative_base()

In [2]: from sqlalchemy.ext.declarative import declarative_base

In [3]: Base = declarative_base(metaclass=RenamingDeclarativeMeta)

In [4]: from sqlalchemy import Column, Integer

In [5]: class Foo(Base):
   ...:     __tablename__ = 'foo'
   ...:     id = Column(Integer, primary_key=True)
   ...:     bar_baz_1 = Column(Integer, nullable=False)
   ...:     

In [6]: Foo.id
Out[6]: <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7ffb7f770e60>

In [7]: Foo.bar_baz_1
Out[7]: <sqlalchemy.orm.attributes.InstrumentedAttribute at 0x7ffb7dc47200>

In [8]: list(Foo.__table__.columns)
Out[8]: 
[Column('Id', Integer(), table=<foo>, key='id', primary_key=True, nullable=False),
 Column('BarBaz1', Integer(), table=<foo>, key='bar_baz_1', nullable=False)]

另一种方法是使用Table对连接到event API对象的所有列进行全局重命名:

from sqlalchemy import event

@event.listens_for(Column, 'before_parent_attach')
def receive_column_before_table_attach(column, table):
    # As dumb as it gets. Blindly modifies all columns.
    column.name = to_camelcase(column.name)

这有一个主要缺点:它也会盲目地重命名反射表中的列,这就是为什么我建议使用元类方法的原因。它包含的更好,也就不足为奇了。