How to jsonify objects from sqlalchemy?

后端 未结 6 557
离开以前
离开以前 2021-01-21 23:15

I\'m using Flask, SQLAlchemy and javascript. I need to pass the results of my query to javascript in the json format, through AJAX, but I keep getting this error:



        
6条回答
  •  孤城傲影
    2021-01-21 23:56

    After some more fiddling around, I fixed it, here's how:

    @app.route('/past/')
    def get_past_clouds(user_id):
        if user_id:
            clouds = model_session.query(model.User).filter_by(id=user_id).first().clouds
            if clouds != "":
                clouds_d = {}
                for idx, cloud in enumerate(clouds):
                    clouds_d[idx] = [ photo.path + photo.filename for photo in cloud.photos ]
                print "clouds: ", clouds_d
                return json.dumps(clouds_d)
        return None
    

    It looks like SQLAlchemy objects are not serializable, so I had to get out exactly what I wanted from the objects it was returning.

提交回复
热议问题