Skip to content

Instantly share code, notes, and snippets.

@calebdre
Created May 13, 2015 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calebdre/4c66b7ebcc6a5b767434 to your computer and use it in GitHub Desktop.
Save calebdre/4c66b7ebcc6a5b767434 to your computer and use it in GitHub Desktop.
Serialize a SqlAlchemy Query
def serialize(query):
# we wantto transform a sqlalchemy query set into something that can be turned into json
serialized = []
for result in query:
# Strategy: get all the columns on the model and put them in a dictionary.
# Then get the relation models and do the same thing, adding them to the master dictionary
s = {}
relations = result.__mapper__.relationships._data.keys()
columns = result.__table__.columns._data.keys()
table = result.__table__.name
for c in columns:
if c == "timestamp":
# convert timestamp object to an actual timestamp
attr = (getattr(result, c) - datetime(1970,1,1)).total_seconds()
else:
attr = getattr(result, c)
s[c] = attr
if(relations):
for relation in relations:
s[relation] = []
relationModels = []
relationModels.append(getattr(result, relation))
if len(relationModels) == 1:
try:
# we're going to check if there's only 1 item, and then if there is we're
# going to check if that object is an object. if it's not, then it's a list
# and we don't need lists inside of lists.
len(relationModels[0])
relationModels = relationModels[0]
except TypeError:
pass
for model in relationModels:
modelDict = unpack_model(model)
s[relation].append(modelDict)
serialized.append(s)
if len(serialized) == 1:
return serialized[0]
return serialized
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment