在SQLAlchemy中使用cdecimal

2024-06-26 04:30:56 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我尝试使用cdecimal在我的数据库中存储货币值。SQLAlchemy Doc

import sys
import cdecimal
sys.modules["decimal"] = cdecimal

我将PostgreSQL数据库连接成这样:

^{pr2}$

我已经建立了这样的模型:

class Exchange(Base):
    amount = Column(Numeric)
    ...

    def __init__(self, amount):
        self.amount = cdecimal.Decimal(amount)

但是,每次执行此操作时,都会出现以下错误:

ProgrammingError: (ProgrammingError) can't adapt type 'cdecimal.Decimal' 'INSERT INTO...

我做错什么了?在


Tags: importselfmodules数据库docsqlalchemypostgresqlsys
1条回答
网友
1楼 · 发布于 2024-06-26 04:30:56

这个对我有用请试试这个

import sys 
import cdecimal
sys.modules["decimal"] = cdecimal

from sqlalchemy import create_engine, Numeric, Integer, Column
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('mysql://test:test@localhost/test1')
Base = declarative_base()


class Exchange(Base):
    __tablename__ = 'exchange'
    id = Column(Integer, primary_key=True)
    amount = Column(Numeric(10,2))

    def __init__(self, amount):
        self.amount = cdecimal.Decimal(amount)


Base.metadata.create_all(engine)
from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind=engine)
session = Session()


x = Exchange(10.5)
session.add(x)
session.commit()

注意:我的电脑中没有pgsql,所以我尝试了mysql。在

相关问题 更多 >