Flask-Restful - Return json with nested array

廉价感情. 提交于 2021-01-28 04:08:05

问题


My model consists in users and books. I want to nest all the books as an array of objects inside each user object, in order to show the books that each user owns. I'm trying to use marshal to nest the books as a list inside the users fields but nothing happens. In the response, there is only the array of users but no track of books and neither of an error. The idea is this:

books_fields = {
    'id': fields.Integer,
    'type' : fields.String,
    'created_at': fields.DateTime,
    'user_id' : fields.Integer
}

users_fields = {
    'id': fields.Integer,
    'name' : fields.String,
    'created_at': fields.DateTime,
    'books': fields.List(fields.Nested(books_fields))
}


users = session.query(model.Users).outerjoin(model.Cities)
         .filter_by(weather = args.weather).all()

for user in users:
    books = session.query(model.Books).outerjoin(model.Users)
             .filter_by(user_id = user.id).all()
    user.books = marshal(books, books_fields)


return {'users': marshal(users, users_fields)}, 200

The issue is that books don't appear.


回答1:


I believe you need to manually create a dictionary for users. Marshal has never worked for me in this manner (this is assuming your books query is returning rows).

Try something like this:

books_fields = {
    'id': fields.Integer,
    'type' : fields.String,
    'created_at': fields.DateTime,
    'user_id' : fields.Integer
}

users_fields = {
    'id': fields.Integer,
    'name' : fields.String,
    'created_at': fields.DateTime,
    'books': fields.List(fields.Nested(books_fields))
}

users_dict = {}

users = session.query(model.Users).outerjoin(model.Cities)
         .filter_by(weather = args.weather).all()

for user in users:
    books_dict = {}
    books = session.query(model.Books).outerjoin(model.Users)
             .filter_by(user_id = user.id).all()
    for book in books:
        book_dict = {
            'id': book.id,
            'type': book.type,
            'created_at': book.created_at
        }
        books_dict.append(book_dict)

    user_dict = {
        'id': user.id,
        'name': user.name,
        'created_at': user.created_at,
        'books': books_dict
    }
    users_dict.append(user_dict)

return {'users': marshal(users_dict, users_fields)}, 200 


来源:https://stackoverflow.com/questions/36065403/flask-restful-return-json-with-nested-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!