Skip to content

Commit

Permalink
The default amount should be set via defaults (#257)
Browse files Browse the repository at this point in the history
  • Loading branch information
kjagiello authored and Stranger6667 committed Jan 31, 2017
1 parent ef3c2f3 commit 44a0a70
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
5 changes: 3 additions & 2 deletions djmoney/models/managers.py
Expand Up @@ -144,11 +144,12 @@ def _expand_money_kwargs(model, args=(), kwargs=None, exclusions=()):
if is_in_lookup(name, value):
args += (_convert_in_lookup(model, name, value), )
del kwargs[name]
elif isinstance(field, CurrencyField):
elif isinstance(field, CurrencyField) and 'defaults' in exclusions:
money_field_name = name[:-9] # Remove '_currency'
if money_field_name not in involved_fields:
money_field = _get_field(model, money_field_name)
kwargs[money_field_name] = money_field.default.amount
kwargs['defaults'] = kwargs.get('defaults', {})
kwargs['defaults'][money_field_name] = money_field.default.amount

return args, kwargs

Expand Down
9 changes: 9 additions & 0 deletions tests/test_models.py
Expand Up @@ -37,6 +37,7 @@
ModelWithDefaultAsStringWithCurrency,
ModelWithNonMoneyField,
ModelWithTwoMoneyFields,
ModelWithUniqueIdAndCurrency,
ModelWithVanillaMoneyField,
NullMoneyFieldModel,
ProxyModel,
Expand Down Expand Up @@ -239,6 +240,14 @@ def test_get_or_create_respects_currency(self, kwargs, currency):
instance, created = ModelWithVanillaMoneyField.objects.get_or_create(**kwargs)
assert str(instance.money.currency) == currency, 'currency should be taken into account in get_or_create'

def test_get_or_create_respects_defaults(self):
instance = ModelWithUniqueIdAndCurrency.objects.create(money=Money(0, 'SEK'))
_, created = ModelWithUniqueIdAndCurrency.objects.get_or_create(
id=instance.id,
money_currency=instance.money_currency
)
assert not created

def test_defaults(self):
money = Money(10, 'EUR')
instance, _ = ModelWithVanillaMoneyField.objects.get_or_create(integer=1, defaults={'money': money})
Expand Down
7 changes: 7 additions & 0 deletions tests/testapp/models.py
Expand Up @@ -27,6 +27,13 @@ class ModelWithDefaultAsInt(models.Model):
money = MoneyField(default=123, max_digits=10, decimal_places=2, default_currency='GHS')


class ModelWithUniqueIdAndCurrency(models.Model):
money = MoneyField(default=123, max_digits=10, decimal_places=2, default_currency='GHS')

class Meta:
unique_together = ('id', 'money')


class ModelWithDefaultAsStringWithCurrency(models.Model):
money = MoneyField(default='123 USD', max_digits=10, decimal_places=2)

Expand Down

0 comments on commit 44a0a70

Please sign in to comment.