I’m trying to find a way to convert dataclass
fields both pre and post SQLAlchemy
queries.
Let’s say I have this table:
create table Products (
id bigint primary key not null,
productName text,
productPrice bigint
);
And then let’s say that this dataclass
is used to represent the table.
from decimal import *
from dataclasses import dataclass
from sqlalchemy import Table, Column, Integer, String
from sqlalchemy.orm import registry
mapper_registry = registry()
@mapper_registry.mapped
@dataclass
class Product():
__table_args__ = {'quote':False}
__table__ = Table(
"Products",
mapper_registry.metadata,
Column("id", Integer, primary_key=True),
Column("productName", String),
Column("productPrice", Integer),
)
id: int = 0
productName: str = ''
productPrice: Decimal = Decimal('0')
In my tables I use a bigint
to represent the currency while in the dataclass
I want it represented as Decimal
. So ideally, when I use SQLAlchemy
to insert
a new product the productPrice
will be converted to int
by multiplying it by 100 and then casting while on select
operations, the column should be divided by 100 and casted back to Decimal
.
I don’t believe __post_init__
will fully solve my problem so I’m not sure this is possible in Python and maybe instead something that can be done within Postgres itself?
1