How should I handle decimal in SQLalchemy & SQLite

后端 未结 3 1068
慢半拍i
慢半拍i 2020-12-24 07:21

SQLalchemy give me the following warning when I use a Numeric column with an SQLite database engine.

SAWarning: Dialect sqlite+pysqlite does not

3条回答
  •  庸人自扰
    2020-12-24 07:58

    from decimal import Decimal as D
    import sqlalchemy.types as types
    
    class SqliteNumeric(types.TypeDecorator):
        impl = types.String
        def load_dialect_impl(self, dialect):
            return dialect.type_descriptor(types.VARCHAR(100))
        def process_bind_param(self, value, dialect):
            return str(value)
        def process_result_value(self, value, dialect):
            return D(value)
    
    # can overwrite the imported type name
    # @note: the TypeDecorator does not guarantie the scale and precision.
    # you can do this with separate checks
    Numeric = SqliteNumeric
    class T(Base):
        __tablename__ = 't'
        id = Column(Integer, primary_key=True, nullable=False, unique=True)
        value = Column(Numeric(12, 2), nullable=False)
        #value = Column(SqliteNumeric(12, 2), nullable=False)
    
        def __init__(self, value):
            self.value = value
    

提交回复
热议问题