Reputation: 989
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.
class Money(Decimal):
# logic here
class Wallet:
# other attributes
balance: Money
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
?
Upvotes: 2
Views: 1155
Reputation: 765
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
Upvotes: 3