我正在使用 flask-marshmallow
.
作为回应,我得到下一个类似的 json
:
data = {
'id': '1.0.1',
'name': 'test',
'applicaion_id': 'google',
}
我怎样才能得到
application.name
来自 Application
?react
class VersionDetail extends Component {
state = {
app: {
id: '',
name: '',
application_id: '',
}
}
componentDidMount() {
axios.get('/apps/'+this.props.match.params.id)
.then(response => this.setState({ app: response.data }))
.catch(function (error) {
})
}
render() {
return ()
}
}
路线
class ApplicationDetailSchema(ma.ModelSchema):
class Meta:
model = Application
fields = ('id', 'name', 'versions')
class VersionDetailSchema(ma.ModelSchema):
class Meta:
model = Version
fields = ('id', 'file', 'application_id')
version_schema = VersionDetailSchema()
@app.route("/<application_id>/<version_id>")
def version_detail(id):
application = Application.get(application_id)
version = Version.get(version_id)
return version_schema.dump(version)
型号
class Application(db.Model):
__tablename__ = 'applications'
id = db.Column(db.String(), primary_key=True)
name = db.Column(db.String())
versions = db.relationship('Version', backref='application', lazy=True)
def __repr__(self):
return '<application {}>'.format(self.name)
class Version(db.Model):
__tablename__ = 'versions'
id = db.Column(db.String(), primary_key=True)
file = db.Column(db.String(80), nullable=True)
application_id = db.Column(db.Integer, db.ForeignKey('applications.id'))
def __repr__(self):
return '<version {}>'.format(self.id)
最佳答案
我认为您需要添加 ma.Nested
架构到您的 VersionDetailSchema
,如 this answer 中所述- 就像是;
class VersionDetailSchema(ma.ModelSchema):
application = ma.Nested(ApplicationDetailsSchema, only=['name'])
class Meta:
model = Version
fields = ('id', 'file', 'application_id', 'application')
我只是猜测
only=['name']
基于marshmallow docs不幸的是,关于
flask-marshmallow
的文档并不多。 - 我个人发现使用该插件的好处实际上不如文档更详细的 marshmallow
就其本身而言 - 设置几乎不是很困难。
关于reactjs - 如何从关系模型中获取其他字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58401965/