reactjs - 如何从关系模型中获取其他字段?

标签 reactjs flask flask-restful

我正在使用 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/

相关文章:

javascript - 增加数组中对象的数量Javascript,React,RecoilJs

python - 如何安全地在具有代理的Flask中获取用户的IP地址?

python - 打印以查看 BigQuery 查询的结果

javascript - 谁能帮助我如何在 Meteor React 应用程序中使用 jQuery-formBuilder 插件

javascript - 如何将上下文绑定(bind)到事件处理程序,以便将事件和更多参数传递给处理程序函数

javascript - react 路由器错误 - 'Cannot call method ' getRouteAtDepth' of undefined'

loops - 相当于Jinja中的此循环

python - Python (Flask) 中的 Get 和 Post 方法

python - linux python3错误; "OSError [Errno 98]"或 "The kernel process exited. (0)"

python - 无法使用 Flask Blueprints 和 Swagger UI 获取 API 规范