Flask-SQLAlchemy and Flask-Restless don't force grandchildren

Problem

I am building an application in Flask, Flask-SQLAlchemy and Flask-Restless. I used worry to create an API for a parent-child-grandson relationship *. The GET for my child will correctly deliver the grandson, but the GET for the parent will not receive the grandson for each child.

* In fact, parent-child relationships are many-to-many, but the same thing.

Models

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 / child response

{
  "num_results": 1, 
  "objects": [
    {
      "id": 1, 
      "name": "test"
      "grandchild": {
        "id": 1, 
        "name": "test"
      }
    }
  ], 
  "page": 1, 
  "total_pages": 1
}

GET: / api / parent answer

{
  "num_results": 1, 
  "objects": [
    {
      "children": [
        {
          "id": 1, 
          "name": "test", 
          "grandchild_id": 1
        }
      ],
      "id": 1, 
      "name": "test"
    }], 
  "page": 1, 
  "total_pages": 1
}
+4
source share
2 answers

postprocessors can be used to retrieve a grandson.

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]})
+9
source

, , . -, , , , :

https://github.com/jfinkels/flask-restless/pull/222#issuecomment-31326359 @jfinkels, , , , , , .

, , , API (, , , , ).

FWIW, Flask-Classy json API , . , , , , , .

+2

Source: https://habr.com/ru/post/1533866/


All Articles