Search code examples
pythondatabasereturnreturn-value

return from database only one value


I want to return only one value from db

Hi i have python code:

@app.route('/actor_genre_list/<int:id>', methods=['GET'])
def actor_genre_list(id):
    genre_id = queries.get_actor_genres(id)
    for idx, element in enumerate(genre_id):
        print(genre_id[idx])
    #for element in genres:
    #    print(int(genres[element].genre_id))
    return jsonify(genre_id=genre_id)

and it return from db: RealDictRow([('show_id', 1390), ('actor_id', 9739), ('genre_id', 1)])

I want it to return only values od 'genre_id'


Solution

  • To return only the values of the 'genre_id' from the database result, you can modify your code as follows:

    @app.route('/actor_genre_list/<int:id>', methods=['GET'])
    def actor_genre_list(id):
        genre_id = queries.get_actor_genres(id)
        genre_ids = [row['genre_id'] for row in genre_id]
        return jsonify(genre_ids=genre_ids)
    

    In this modified code, a list comprehension is used to extract the 'genre_id' values from each row of the genre_id result. The resulting list of genre IDs is then returned in the JSON response with the key 'genre_ids'.