12

我有一个 MSSQL 数据库,其中包含我无法更改的表,并且只能以只读方式与其交互(SELECT 语句)。我正在使用 sqlalchemy。我需要做的是为每个查询自动包装 CAST() SQL 操作中的特定列。我想在低级别执行此操作,因此我的代码永远不需要考虑问题。这个问题解释了我这样做的原因。

我的桌子是这样的:

from sqlalchemy import Column, Integer, Sequence
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class myTable(Base):
    __tablename__ = u'mytable'
    id = Column(Integer, Sequence('table_id_seq'), primary_key=True)
    problem_field = Column(DECIMAL(12, 4), nullable=True)

我一直在尝试使用这样的 TypeDecorator:

from sqlalchemy import Column, Integer, Sequence, types
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.expression import cast

Base = declarative_base()

class CastToFloatType(types.TypeDecorator):
    '''Converts stored Decimal values to Floats via CAST operation
    '''
    impl = types.Numeric
    def column_expression(self, col):
        return cast(col, Float)

class myTable(Base):
    __tablename__ = u'mytable'
    id = Column(Integer, Sequence('table_id_seq'), primary_key=True)
    wrapped_field = Column(CastToFloatType, nullable=True)

但它似乎没有做任何事情。

4

1 回答 1

10

我认为您需要确保您至少使用 0.8 版的 SQLAlchemy,其中column_expression()添加了该功能。为此,对您的代码进行简单的测试:

from sqlalchemy import Column, Integer, Sequence, types, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql.expression import cast

Base = declarative_base()

class CastToFloatType(types.TypeDecorator):
    '''Converts stored Decimal values to Floats via CAST operation
    '''
    impl = types.Numeric
    def column_expression(self, col):
        return cast(col, Float)

class myTable(Base):
    __tablename__ = u'mytable'
    id = Column(Integer, Sequence('table_id_seq'), primary_key=True)
    wrapped_field = Column(CastToFloatType, nullable=True)

from sqlalchemy.orm import Session
s = Session()
print s.query(myTable)

输出:

SELECT mytable.id AS mytable_id, CAST(mytable.wrapped_field AS FLOAT) AS mytable_wrapped_field 
FROM mytable
于 2013-11-15T17:50:04.057 回答