Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 507
forkfork Avatar asked Dec 13 '25 02:12

forkfork


1 Answers

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 
like image 134
Kelly Keller-Heikkila Avatar answered Dec 15 '25 16:12

Kelly Keller-Heikkila



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!