how are u doing?
I've been developing some software using the classical mapping
from SQLAlchemy
and I want to know how can I map a database value to my own value object class.
For example, I have a Wallet
class that has a Money
attribute that is a value object.
domain
class Money(Decimal):
# logic here
class Wallet:
# other attributes
balance: Money
mapper
wallet_table = Table(
'wallet',
metadata,
Column('id', UUIDType, primary_key=True),
Column('balance', Numeric, nullable=False)
)
wallet_mapper = mapper(Wallet, wallet_table)
How do I tell SQLAlchemy
that when querying for this data on the database it should return balance
as a Money
?
asked Mar 8, 2021 at 21:52
1 Answer 1
You can do that with TypeDecorator
:
from sqlalchemy.types import TypeDecorator, NUMERIC
class Money:
value: float # Don't know the type you want but let's say it's a float
# some logic
class MoneyDecorator(TypeDecorator):
impl = NUMERIC
def process_bind_param(self, money: Money, dialect) -> float:
if money is not None:
return money.value
def process_result_value(self, value: float, dialect) -> Money:
if value is not None:
return Money(value)
wallet_table = Table(
'wallet',
metadata,
Column('id', UUIDType, primary_key=True),
Column('balance', MoneyDecorator, nullable=False)
)
wallet_mapper = mapper(Wallet, wallet_table)
Then you can do inserts and selects this way:
stmt = wallet_table.insert({'balance': Money(123.4)})
session.execute(stmt)
stmt = wallet_table.select()
result = sesion.execute(stmt)
print(result.first()['balance'].value) # Prints: 123.4
answered Mar 8, 2021 at 22:27
1 Comment
gbrennon
thank u man! this was an amazing contribution!
lang-py