问题
我正在烧瓶上建立一个应用程序,烧瓶sqlalchemy和烧瓶不宁。我用untist为亲子孙关系生成了一个api*。上我的孩子会正确地把孙子接回来,但上父母不会为每个孩子接孙子。
*事实上,亲子关系是多对多,但前提相同。
模型

class Grandchild(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)

    parent = db.relationship('Child', backref='grandchild')

parent_child = db.Table('parent_child',
    db.Column('parent_id', db.Integer, db.ForeignKey('parent.id')),
    db.Column('child_id', db.Integer, db.ForeignKey('child.id')),
    db.Column('number', db.SmallInteger)
)

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)

    grandchild_id = db.Column(db.Integer, db.ForeignKey('grandchild.id'), nullable=False)

class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String, nullable=False)

    children = db.relationship('Child', secondary=parent_child)

api.create_api(Child, exclude_columns=['grandchild_id'])
api.create_api(Parent)

get:/api/子响应
{
  "num_results": 1,
  "objects": [
    {
      "id": 1,
      "name": "test"
      "grandchild": {
        "id": 1,
        "name": "test"
      }
    }
  ],
  "page": 1,
  "total_pages": 1
}

get:/api/父响应
{
  "num_results": 1,
  "objects": [
    {
      "children": [
        {
          "id": 1,
          "name": "test",
          "grandchild_id": 1
        }
      ],
      "id": 1,
      "name": "test"
    }],
  "page": 1,
  "total_pages": 1
}

最佳答案

postprocessors可用于获取孙子。

def parent_post_get_many(result=None, search_params=None, **kw):
   for object in result['objects']:
      for child in object['children']:
         grandchild = Grandchild.query.get(child['grand_child_id'])
         child.update({'grandchild': grandchild})

api.create_api(Parent, postprocessors={'GET_MANY': [parent_post_get_many]})

09-25 17:49