Skip to content

Instantly share code, notes, and snippets.

@Hispar
Created October 9, 2018 08:28
Show Gist options
  • Save Hispar/33f78fc73e31b4406b952eaa279d154a to your computer and use it in GitHub Desktop.
Save Hispar/33f78fc73e31b4406b952eaa279d154a to your computer and use it in GitHub Desktop.
Working with django money and django graphene
import graphene
from graphene_django import DjangoObjectType
class Money(graphene.Scalar):
@staticmethod
def serialize(value):
return value
@staticmethod
def parse_literal(node):
return node
@staticmethod
def parse_value(value):
return value
@staticmethod
def resolve(value):
result = {
'amount': 0,
'currency': 'USD',
}
if value is None:
return result
result['currency'] = str(value.currency)
try:
result['amount'] = float(value.amount)
except ValueError:
return result
return result
class ModelType(DjangoObjectType):
cost = graphene.Field(Money)
class Meta:
name = 'model'
model = Model
interfaces = (graphene.relay.Node,)
only_fields = [
'id',
'cost'
]
filter_fields = [
'id',
]
def resolve_cost(self, info):
return Money.resolve(self.cost)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment