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

时间:2019-10-15 20:07:46

标签: reactjs flask flask-restful

我正在使用flask-marshmallow

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

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

如何从application.name获得Application

反应

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)

1 个答案:

答案 0 :(得分:1)

我认为您需要向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')

我只是基于marshmallow docs

来猜测only=['name']

不幸的是,flask-marshmallow的文档记录方式不多-我个人发现,使用该附件的好处实际上比记录得更好的marshmallow本身要少-设置很难很难。