如何在SQLalchemy&中处理小数SQLite的 [英] How should I handle decimal in SQLalchemy & SQLite
问题描述
当我在SQLite数据库引擎中使用数值列时,SQLalchemy给我以下警告。
SQLalchemy give me the following warning when I use a Numeric column with an SQLite database engine.
SAWarning:方言sqlite + pysqlite可以不本机支持小数对象
我正在尝试找出拥有<$ c的最佳方法$ c> pkgPrice = Column(Numeric(12,2))在仍使用SQLite的同时在SQLalchemy中。
I'm trying to figure out the best way to have pkgPrice = Column(Numeric(12,2))
in SQLalchemy while still using SQLite.
此问题[1] 如何将Python十进制转换为SQLite数字?显示了一种使用方法 sqlite3.register_adapter(D,Adapt_decimal)
使SQLite接收并返回Decimal,但存储字符串,但是我不知道如何挖掘SQLAlchemy核心来做到这一点。类型装饰器看起来像是正确的方法,但是我还不了解它们。
This question [1] How to convert Python decimal to SQLite numeric? shows a way to use sqlite3.register_adapter(D, adapt_decimal)
to have SQLite receive and return Decimal, but store Strings, but I don't know how to dig into the SQLAlchemy core to do this yet. Type Decorators look like the right approach but I don't grok them yet.
是否有人拥有SQLAlchemy类型装饰器配方,该配方在SQLAlchemy模型中将具有数字或十进制数字,但将它们作为字符串存储在SQLite中?
Does anyone have a SQLAlchemy Type Decorator Recipe that will have Numeric or Decimal numbers in the SQLAlchemy model, but store them as strings in 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, 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
这篇关于如何在SQLalchemy&中处理小数SQLite的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!