在SQLalchemy&SQLite中应该如何处理小数

前端之家收集整理的这篇文章主要介绍了在SQLalchemy&SQLite中应该如何处理小数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我使用带有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中?

  1. from decimal import Decimal as D
  2. import sqlalchemy.types as types
  3.  
  4. class sqliteNumeric(types.TypeDecorator):
  5. impl = types.String
  6. def load_dialect_impl(self,dialect):
  7. return dialect.type_descriptor(types.VARCHAR(100))
  8. def process_bind_param(self,value,dialect):
  9. return str(value)
  10. def process_result_value(self,dialect):
  11. return D(value)
  12.  
  13. # can overwrite the imported type name
  14. # @note: the TypeDecorator does not guarantie the scale and precision.
  15. # you can do this with separate checks
  16. Numeric = sqliteNumeric
  17. class T(Base):
  18. __tablename__ = 't'
  19. id = Column(Integer,primary_key=True,nullable=False,unique=True)
  20. value = Column(Numeric(12,2),nullable=False)
  21. #value = Column(sqliteNumeric(12,nullable=False)
  22.  
  23. def __init__(self,value):
  24. self.value = value

猜你在找的Sqlite相关文章