AKhimself
AKhimself

Reputation: 165

How to add many to one relation of same model to Flask-Restful marshaller?

I have a Category model, which can have a children, who also a Category model:

    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)

So I have many to one relation. And I want to marshall it with Flask-Restful:

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

How to describe subcategories in marshaller?

Upvotes: 0

Views: 471

Answers (1)

junnytony
junnytony

Reputation: 3535

I would try using fields.List and fields.Nested.

Example:

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))

Upvotes: 2

Related Questions