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've connected my PostgreSQL database like so:
sqlalchemy.url = postgresql+psycopg2://user:password@host:port/dbname
I've set up the model something like this:
class Exchange(Base):
amount = Column(Numeric)
...
def __init__(self, amount):
self.amount = cdecimal.Decimal(amount)
However, whenever I do this, I get the following error:
ProgrammingError: (ProgrammingError) can't adapt type 'cdecimal.Decimal' 'INSERT INTO...
What am I doing wrong?
This one is working 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 dont have pgsql in my pc so I tried on mysql.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With