Last active
August 29, 2015 14:10
-
-
Save miraculixx/81ae7680d412255ea36f to your computer and use it in GitHub Desktop.
MoneyField for tastypie
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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