我应该如何处理 SQLalchemy & 中的小数点SQLite

How should I handle decimal in SQLalchemy amp; SQLite(我应该如何处理 SQLalchemy amp; 中的小数点SQLite)
本文介绍了我应该如何处理 SQLalchemy & 中的小数点SQLite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用带有 SQLite 数据库引擎的 Numeric 列时,SQLalchemy 给了我以下警告.

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

SAWarning:方言 sqlite+pysqlite 不原生支持 Decimal 对象

SAWarning: Dialect sqlite+pysqlite does not support Decimal objects natively

我正在尝试找出在 SQLalchemy 中使用 SQLite 的同时使用 pkgPrice = Column(Numeric(12,2)) 的最佳方法.

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

FastAPI + Tortoise ORM + FastAPI Users (Python) - Relationship - Many To Many(FastAPI+Tortoise ORM+FastAPI用户(Python)-关系-多对多)
Window functions not working in pd.read_sql; Its shows error(窗口函数在pd.read_sql中不起作用;它显示错误)
(Closed) Leaflet.js: How I can Do Editing Geometry On Specific Object I Select Only?((已关闭)Leaflet.js:如何仅在我选择的特定对象上编辑几何图形?)
in sqlite update trigger with multiple if/Case Conditions(在具有多个IF/CASE条件的SQLite UPDATE触发器中)
Android: Why is Room so slow?(Android:为什么Room这么慢?)
Remote Procedure call failed with sql server 2008 R2(使用 sql server 2008 R2 的远程过程调用失败)