简体   繁体   English

Flask-Restful - 返回带有嵌套数组的 json

[英]Flask-Restful - Return json with nested array

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.问题是书没有出现。

I believe you need to manually create a dictionary for users .我相信您需要为users手动创建字典。 Marshal has never worked for me in this manner (this is assuming your books query is returning rows). Marshal从来没有以这种方式为我工作过(这是假设您的书籍查询正在返回行)。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM