【问题标题】:How to add many to one relation of same model to Flask-Restful marshaller?如何将同一模型的多对一关系添加到 Flask-Restful 编组器?
【发布时间】:2015-05-26 12:11:21
【问题描述】:

我有一个类别模型,它可以有一个孩子,他们也是一个类别模型:

    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 中描述子类别?

【问题讨论】:

    标签: python flask marshalling relationship flask-restful


    【解决方案1】:

    我会尝试使用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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-28
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2021-01-19
      • 2016-07-12
      相关资源
      最近更新 更多