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

How can I get other fields from relation model?

我正在使用 flask-marshmallow

作为回应,我得到下一个类似的 json:

data = {
    'id': '1.0.1',
    'name': 'test',
    'applicaion_id': 'google',
}

如何从 Application 得到 application.name

反应

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 中,如 中所述 - 类似于;

class VersionDetailSchema(ma.ModelSchema):

  application = ma.Nested(ApplicationDetailsSchema, only=['name'])

  class Meta:
    model = Version
    fields = ('id', 'file', 'application_id', 'application')

我只是根据 marshmallow docs

猜测 only=['name']

不幸的是,关于 flask-marshmallow 的文档并不多 - 我个人发现使用该插件的好处实际上比文档更完善的 marshmallow 本身要少 -设置并不难。