forked from absent1706/sqlalchemy-mixins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserialize.py
31 lines (22 loc) · 834 Bytes
/
serialize.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
from collections import Iterable
from .inspection import InspectionMixin
class SerializeMixin(InspectionMixin):
"""Mixin to make model serializable."""
__abstract__ = True
def to_dict(self, nested=False):
"""Return dict object with model's data.
:param nested: flag to return nested relationships' data if true
:type: bool
:return: dict
"""
result = dict()
for key in self.columns:
result[key] = getattr(self, key)
if nested:
for key in self.relations:
obj = getattr(self, key)
if isinstance(obj, SerializeMixin):
result[key] = obj.to_dict()
elif isinstance(obj, Iterable):
result[key] = [o.to_dict() for o in obj]
return result