当我使用带有sqlite数据库引擎的Numeric列时,sqlalchemy会给出以下警告.
SAWarning: Dialect sqlite+pysqlite does not support Decimal objects natively
我试图找出在sqlalchemy中仍然使用sqlite的pkgPrice = Column(Numeric(12,2))的最佳方式.
这个问题[1] How to convert Python decimal to SQLite numeric?显示了一种使用sqlite3.register_adapter(D,adapt_decimal)使sqlite接收和返回Decimal但存储Strings的方法,但是我不知道如何挖掘sqlAlchemy核心来做到这一点.类型装饰器看起来像是正确的方法,但我还没有想到他们.
有没有人有sqlAlchemy Type Decorator Recipe,它将在sqlAlchemy模型中具有数字或十进制数字,但将其作为字符串存储在sqlite中?
- 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,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,nullable=False)
- def __init__(self,value):
- self.value = value