在我的 Rest 应用程序中,我想返回像 JSONAPI
格式的 json
,但是我需要为它创建 Schema 类并再次创建我已经存在的每个字段模型
。因此,我不是在模式类中创建每个字段,而是可以不从 DB Model
中获取它..
下面是我的模型类
class Author(db.Model):
id = db.Column(db.Integer)
name = db.Column(db.String(255))
我正在像下面这样定义 Schema。
class AuthorSchema(Schema):
id = fields.Str(dump_only=True)
name = fields.Str()
metadata = fields.Meta()
class Meta:
type_ = 'people'
strict = True
所以这里,id
和name
我定义了两次。那么 marshmallow-jsonapi
中是否有任何选项可以在模式类中分配模型名称,以便它可以从 model
中获取所有字段
注意:我正在为它使用 marshmallow-jsonapi
,我已经尝试过 marshmallow-sqlalchemy
,它有那个选项但它不返回 json
在 JSONAPI
格式
最佳答案
您可以将 flask-marshmallow
的 ModelSchema
和 marshmallow-sqlalchemy
与 marshmallow-jsonapi
结合使用需要注意的是,您不仅必须继承 Schema
类,还必须继承 SchemaOpts
类,如下所示:
# ...
from flask_marshmallow import Marshmallow
from marshmallow_jsonapi import Schema, SchemaOpts
from marshmallow_sqlalchemy import ModelSchemaOpts
# ...
ma = Marshmallow(app)
# ...
class JSONAPIModelSchemaOpts(ModelSchemaOpts, SchemaOpts):
pass
class AuthorSchema(ma.ModelSchema, Schema):
OPTIONS_CLASS = JSONAPIModelSchemaOpts
class Meta:
type_ = 'people'
strict = True
model = Author
# ...
foo = AuthorSchema()
bar = foo.dump(query_results).data # This will be in JSONAPI format including every field in the model
关于python - 从模型中获取 JSONAPI 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47180202/