在SQLAlchemy中使用cdecimal

3

我正在尝试使用cdecimal来存储数据库中的货币值。 SQLAlchemy文档

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

我已经连接了我的PostgreSQL数据库,如下所示:

sqlalchemy.url = postgresql+psycopg2://user:password@host:port/dbname

我已经设置了模型,就像这样:

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...

我做错了什么?

没事了,这与调用它而不是设置它有关。 - Jonathan Ong
1个回答

7
这个对我有效,请尝试一下。
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上尝试了一下。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接