From d294df4761d3ba226005afa4181108e37cc46cc5 Mon Sep 17 00:00:00 2001 From: Keiran Price Date: Thu, 24 Oct 2019 10:25:16 +0100 Subject: [PATCH 1/2] #105: Create serializer method --- common/models/db_models.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/common/models/db_models.py b/common/models/db_models.py index 5d3fce23..223709c4 100644 --- a/common/models/db_models.py +++ b/common/models/db_models.py @@ -1,6 +1,8 @@ import enum from datetime import datetime +from decimal import Decimal + from sqlalchemy import Index, Column, BigInteger, String, DateTime, ForeignKey, Integer, Float, FetchedValue, \ TypeDecorator, Boolean from sqlalchemy.ext.declarative import declarative_base @@ -53,6 +55,19 @@ def to_dict(self): dictionary[column.name] = str(attribute) if isinstance(attribute, datetime) else attribute return dictionary + def _make_serializable(self, field): + """ + Given a field, convert to a JSON serializable type + :param field: The field to be converted + :return: The converted field + """ + if isinstance(field, datetime): + return str(field) + elif isinstance(field, Decimal): + return float(field) + else: + return field + def to_nested_dict(self, includes): """ Given related models return a nested dictionary with the child or parent rows nested. From b78d25106d99404f08cde8ff337a7970470ecd17 Mon Sep 17 00:00:00 2001 From: Keiran Price Date: Thu, 24 Oct 2019 10:25:29 +0100 Subject: [PATCH 2/2] #105: Use method --- common/models/db_models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/common/models/db_models.py b/common/models/db_models.py index 223709c4..23b45696 100644 --- a/common/models/db_models.py +++ b/common/models/db_models.py @@ -52,7 +52,7 @@ def to_dict(self): dictionary = {} for column in self.__table__.columns: attribute = getattr(self, column.name) - dictionary[column.name] = str(attribute) if isinstance(attribute, datetime) else attribute + dictionary[column.name] = self._make_serializable(attribute) return dictionary def _make_serializable(self, field):