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
问题是书籍没有出现.
推荐答案
我相信您需要为用户
手动创建字典. Marshal
从未以这种方式为我工作(这是假设您的图书查询返回了行).
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).
尝试这样的事情:
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
这篇关于Flask-Restful-返回带有嵌套数组的json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!