加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 在SQLAlchemy中使用cdecimal

发布时间:2020-12-20 11:22:39 所属栏目:Python 来源:网络整理
导读:所以我试图使用cdecimal在我的数据库中存储货币值. SQLAlchemy Doc import sysimport cdecimalsys.modules["decimal"] = cdecimal 我连接了我的PostgreSQL数据库,如下所示: sqlalchemy.url = postgresql+psycopg2://user:password@host:port/dbname 我已经
所以我试图使用cdecimal在我的数据库中存储货币值. SQLAlchemy Doc

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

我究竟做错了什么?

解决方法

这个适合我,请试试这个

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读