Using cdecimal in SQLAlchemy

So, I'm trying to use cdecimal to store monetary values ​​in my database. SQLAlchemy Doc

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

I linked my PostgreSQL database like this:

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

I installed the model something like this:

 class Exchange(Base): amount = Column(Numeric) ... def __init__(self, amount): self.amount = cdecimal.Decimal(amount) 

However, when I do this, I get the following error:

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

What am I doing wrong?

+3
source share
1 answer

This one works for me, please try this

 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() 

Note. I do not have pgsql on my computer, so I tried mysql.

+7
source

Source: https://habr.com/ru/post/1401225/


All Articles