-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqlobject_todict.py
34 lines (28 loc) · 1.23 KB
/
sqlobject_todict.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
32
33
34
import datetime
def to_dict(obj):
# each type of column
foreigns = obj.sqlmeta._plainForeignGetters.keys()
joins = obj.sqlmeta.joinDefinitions
# all of the basic stuff is built-in (as I recently discovered -_- )
d = obj.sqlmeta.asDict()
if 'hashed_pass' in d:
del d['hashed_pass']
# convert all datetimes/dates/times to something JSON can use
for k in d:
if isinstance(d[k], datetime.datetime) or isinstance(d[k], datetime.date) or isinstance(d[k], datetime.time):
d[k] = d[k].isoformat()
# function given class and list of objects of that class, returns object dict for that reference
# an object dict is a dictionary with 2 keys. name is the name of the class that the objects contained are instances of
# items is the list of IDs referenced.
def f(klass, objs):
return dict(sqlref=dict(name=klass,
items=[x.id for x in objs]))
# give myself some metadata
d['__meta__'] = dict(name=obj.__class__.__name__, id=obj.id)
# convert all foreign keys to one-element object dicts
for key in foreigns:
d.update({key:f(getattr(obj, key).__class__.__name__, [getattr(obj, key)])})
# convert all joins to object dicts
for key in joins:
d.update({key.name:f(key.kw['otherClass'], getattr(obj, key.name))})
return d