Created
October 9, 2018 08:28
-
-
Save Hispar/33f78fc73e31b4406b952eaa279d154a to your computer and use it in GitHub Desktop.
Working with django money and django graphene
This file contains hidden or 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
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