saran3h
saran3h

Reputation: 14022

Django Money - Add two MoneyFields in different currencies and generate output in given currency

Hi I've been scratching my head over past few days to figure out how to manipulate dj-money fields. Here are my two model fields:

 client_cost = MoneyField(
    _('client cost'),
    max_digits=10,
    decimal_places=2,
    default_currency='AUD',
    null=True,
)

camera_operator_cost = MoneyField(
    _('camera operator cost'),
    max_digits=10,
    decimal_places=2,
    default_currency='AUD',
    null=True,
)

They can have completely different currencies (default being 'AUD').

I need to be able to:

Please help.

PS: I'm using this: https://github.com/django-money/django-money

Upvotes: 1

Views: 2989

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476729

You obtain the Money instances of some_instance with:

money1 = some_instance.client_cost
money2 = some_instance.camera_operator_cost

So we can perform an attribute fetch.

If you install the Exchange rate support, you can then exchange these to a currency, and add these together. For example if the given currency is USD, then we can obtain the sum of the two costs in USD with:

convert_money(money1, 'USD') + convert_money(money2, 'USD')

EDIT

For a Money object, you can obtain the amount and currency with some_money.amount (a Decimal object) and some_money.currency (a Currency object) respectively.

A Currency object attributes like .code, .countries, .name, etc.

If you thus, for example, want to obtain the currency code of money1, you can use:

money1.currency.code  # will be 'USD', 'EUR', 'AUD', etc.

Upvotes: 1

Related Questions