How to jsonify objects from sqlalchemy?

后端 未结 6 571
离开以前
离开以前 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-22 00:22

    As you’ve discovered, SQLAlchemy models are not natively serializable to JSON.

    The approach you adopted - to manually construct a dict from your model instance’s properties - gets the job done, but if you need to jsonify multiple models, deal with value conversions on serialization, or support deserialization (converting JSON back to a SQLAlchemy model instance) you’ll find yourself writing a lot of tedious code.

    A better solution is to use a serialization/deserialization extension library for SQLAlchemy, such as either SQLAthanor or Marshmallow-SQLAlchemy (full disclosure: I am the author of SQLAthanor).

    Using either of these libraries, you can basically serialize and deserialize SQLAlchemy models to other formats or deserialize them back into SQLAlchemy model instances.

    In the case of SQLAthanor, you can basically get the job done with one method call:

    json_result = model_instance.dump_to_json()
    

    or (with some more configuration that gives you more fine-grained control):

    json_result = model_instance.to_json()
    

    You can also serialize to dict, or YAML, or CSV.

    The reverse process is:

    model_instance = ModelClass.new_from_json(json_result)
    

    Hope this helps!

提交回复
热议问题