How to serialize SqlAlchemy result to JSON?

后端 未结 27 2061
说谎
说谎 2020-11-22 09:59

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

27条回答
  •  日久生厌
    2020-11-22 10:20

    I recommend using marshmallow. It allows you to create serializers to represent your model instances with support to relations and nested objects.

    Here is a truncated example from their docs. Take the ORM model, Author:

    class Author(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        first = db.Column(db.String(80))
        last = db.Column(db.String(80))
    

    A marshmallow schema for that class is constructed like this:

    class AuthorSchema(Schema):
        id = fields.Int(dump_only=True)
        first = fields.Str()
        last = fields.Str()
        formatted_name = fields.Method("format_name", dump_only=True)
    
        def format_name(self, author):
            return "{}, {}".format(author.last, author.first)
    

    ...and used like this:

    author_schema = AuthorSchema()
    author_schema.dump(Author.query.first())
    

    ...would produce an output like this:

    {
            "first": "Tim",
            "formatted_name": "Peters, Tim",
            "id": 1,
            "last": "Peters"
    }
    

    Have a look at their full Flask-SQLAlchemy Example.

    A library called marshmallow-sqlalchemy specifically integrates SQLAlchemy and marshmallow. In that library, the schema for the Author model described above looks like this:

    class AuthorSchema(ModelSchema):
        class Meta:
            model = Author
    

    The integration allows the field types to be inferred from the SQLAlchemy Column types.

    marshmallow-sqlalchemy here.

提交回复
热议问题