import datetime import json class Serializer: serializable_fields = [] def get_serializable_fields(self): return self.serializable_fields def get_data(self): data = {} for field in self.get_serializable_fields(): if hasattr(self, field): if isinstance(getattr(self, field), datetime.date): data.update({field: getattr(self, field).isoformat()}) else: data.update({field: getattr(self, field)}) else: raise AttributeError( "This object does not have a field named '{}'".format(field) ) return data def to_json(self): return json.dumps(self.get_data())