Django has some good automatic serialization of ORM models returned from DB to JSON format.
How to serialize SQLAlchemy query result to JSON format?
I tried
A more detailed explanation. In your model, add:
def as_dict(self):
return {c.name: str(getattr(self, c.name)) for c in self.__table__.columns}
The str()
is for python 3 so if using python 2 use unicode()
. It should help deserialize dates. You can remove it if not dealing with those.
You can now query the database like this
some_result = User.query.filter_by(id=current_user.id).first().as_dict()
First()
is needed to avoid weird errors. as_dict()
will now deserialize the result. After deserialization, it is ready to be turned to json
jsonify(some_result)