2

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?

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

thank u man! this was an amazing contribution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.