如何通过查询数据库来使用flask.jsonify返回嵌套的json?

wz1wpwve  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(463)

下面是我的数据库表架构 Movie (id, movie_name, genre, time, channel) 我有一个 MySQL 表并希望返回嵌套的 json 到api,按流派和频道对它们进行分组。
例如:

[
    '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'}]
    }
]

对于每个通道也是如此。
更新:我没有使用sql炼金术,我现在所做的只是 return jsonify(cursor.fetchall())

rta7y2nd

rta7y2nd1#

下面是另一种更具扩展性的方法:

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)

它回来了

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

bejyjqdl2#

假设您使用的是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})

我希望这能引导你,或者至少给你一个起点

相关问题