Skip to content

Instantly share code, notes, and snippets.

@miraculixx
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miraculixx/81ae7680d412255ea36f to your computer and use it in GitHub Desktop.
Save miraculixx/81ae7680d412255ea36f to your computer and use it in GitHub Desktop.
MoneyField for tastypie
from decimal import Decimal
from moneyed.classes import Money
from tastypie.fields import CharField, DecimalField
from tastypie.resources import ModelResource
from djmoney.models.fields import MoneyField as ModelMoneyField
class MoneyFieldMixin(object):
"""
a mixin to enable moneyfields in tastypie ModelResources
use as follows:
class MyModelResource(MoneyFieldMixin, ModelResource):
...
This will automatically convert any MoneyField into and from the respective
serialization format:
{
'amount' : Decimal(...),
'currency' : "XYZ"
}
Solves this TypeError:
File "/tmp/env/local/lib/python2.7/site-packages/tastypie/fields.py", line 262, in convert
return Decimal(value)
File "/usr/lib/python2.7/decimal.py", line 658, in __new__
raise TypeError("Cannot convert %r to Decimal" % value)
TypeError: Cannot convert 100 EUR to Decimal
"""
@classmethod
def api_field_from_django_field(cls, f, default=CharField):
result = ModelResource.api_field_from_django_field(f, default=default) # @UndefinedVariable
if isinstance(f, ModelMoneyField):
result = ApiMoneyField
return result
class ApiMoneyField(DecimalField):
"""
MoneyField tastypie conversion
"""
dehydrated_type = 'money'
help_text = 'Money with amount and currency'
def convert(self, value):
if value is None:
return None
return {
'amount' : Decimal(value.amount),
'currency' : value.currency,
}
def hydrate(self, bundle):
amount = bundle['amount']
value = Money(amount.get('amount'), amount.get('currency'))
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment