如何向Flask-Restful marshaller添加多个相同模型的关系?

时间:2015-05-26 12:11:22

标签: python flask marshalling relationship flask-restful

我有一个分类模型,可以有一个孩子,也是一个分类模型:

    class Category(db.Model):
      id = db.Column(db.Integer, primary_key = True)
      name = db.Column(db.String(32), nullable=False)
      description = db.Column(db.String(128), nullable=True)
      is_folder = db.Column(db.Boolean(), default=False)
      parent_id = db.Column(db.Integer, db.ForeignKey('category.id'))
      subcategories = db.relationship('Category', backref='parent', remote_side=[id], uselist=True)

所以我有多对一的关系。我想用Flask-Restful来编组它:

category_fields = {
  'id': fields.Integer,
  'name': fields.String,
  'description': fields.String,
  'parent_id': fields.Integer,
  'is_folder': fields.Boolean,
  'subcategories': ???,
}

如何在marshaller中描述子类别?

1 个答案:

答案 0 :(得分:2)

我会尝试使用fields.Listfields.Nested

示例:

category_fields = {
   'id': fields.Integer,
   'name': fields.String,
   'description': fields.String,
   'parent_id': fields.Integer,
   'is_folder': fields.Boolean,
}
category_fields['subcategories'] = fields.List(fields.Nested(category_fields))