0

Here is what my database table schema

Movie (id, movie_name, genre, time, channel)

I have a MySQL table and want to return a nested json to an API, grouping them by genre and channel.

For example:

[
    'comedy': {
        [{'id': 1, 'movie_name': 'm1', 'time': 18:00, 'channel': 'c1'},
         {'id': 1, 'movie_name': 'm2', 'time': 18:00, 'channel': 'c2'}]
    },
    'horror': {
        [{'id': 1, 'movie_name': 'm3', 'time': 18:00, 'channel': 'c1'},
         {'id': 1, 'movie_name': 'm4', 'time': 18:00, 'channel': 'c2'}]
    }
]

And similarly for each channels.

Update: I am not using SQL-Alchemy, all I am doing now is return jsonify(cursor.fetchall())

2 Answers 2

1

Assuming you are using SQLAlchemy ORM

comedies = []
horrors =[] #for lack of a better way to put it
all_movies = session.query(Movie)
for movie in all_movies:
   if movie.genre == 'comedy':
      comedy_entry ={'id':movie.id,
                      'movie_name':movie.movie_name,
                      'time':movie.time,
                      'channel': movie.channel }
      comedies.append(comedy_entry)
   if movie.genre == 'horror':
      horror_entry ={'id':movie.id,
                      'movie_name':movie.movie_name,
                      'time':movie.time,
                      'channel': movie.channel }
      horrors.append(horror_entry)

return jsonify({'comedy'= comedies, 'horror'= horrors})

I hope that guides you or at least gives you a starting point

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your solution but can you suggest me an alternative solution without using SQL-Alchemy?
@SagunShrestha please see this answer on how you can connect to mysql database. Answer 3 looks best if you do not want to use SQLAlchemy. The results becomes what you iterate over (equivalent to all movie's above)
0

Here is another, more extendible approach:

columns_to_be_jsonified = ['id', 'movie_name', 'time']
genredict = {}

for movie in Movie.query.all():
    movietup = movie.genre, movie.channel
    moviedict = {}
    for column in columns_to_be_jsonified:
        moviedict[column] = getattr(movie, column)

    if movietup in genredict:
        genredict[movietup].append(moviedict)
    else:
        genredict[movietup] = [moviedict]

return jsonify(genredict)

It returns

{('horror', 'channel1'): [{'id': 1, 'movie_name': 'it', 'time': '18:00'}, {'id': 2, 'movie_name': 'the ring', 'time': '20:00'}],
 ('comedy', 'channel2'): [...]}

1 Comment

Thank you for your solution but can you suggest me an alternative solution without using SQL-Alchemy?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.