22 lines
No EOL
674 B
Python
22 lines
No EOL
674 B
Python
def serialize(obj, *, fields=None, expand=None):
|
|
expand = set(expand or [])
|
|
fields = set(fields or [])
|
|
out = {}
|
|
# base columns
|
|
for col in obj.__table__.columns:
|
|
name = col.key
|
|
if fields and name not in fields:
|
|
continue
|
|
out[name] = getattr(obj, name)
|
|
# expansions
|
|
for rel in obj.__mapper__.relationships:
|
|
if rel.key not in expand:
|
|
continue
|
|
val = getattr(obj, rel.key)
|
|
if val is None:
|
|
out[rel.key] = None
|
|
elif rel.uselist:
|
|
out[rel.key] = [serialize(child) for child in val]
|
|
else:
|
|
out[rel.key] = serialize(val)
|
|
return out |