0

我在 Flask 中做一个项目,我对 Flask-SQLAlchemy 有困难。

class Films(db.Model):
    """Main film table"""
    __tablename__ = 'films'
    film_id = db.Column(db.Integer, primary_key=True)
    film_name = db.Column(db.Text, unique=False, nullable=False, index=True)
class Genres(db.Model):
    """Table with genres"""
    __tablename__ = 'genres'
    genre_id = db.Column(db.Integer, primary_key=True)
    genre_name = db.Column(db.String(20), unique=True, nullable=False)
    gen_films = db.relationship(
        'Films', secondary=films_genres, lazy='subquery',
        backref=db.backref('gen_films', lazy='joined'))
# Association table for table films and table genres
films_genres = db.Table(
    'films_genres',
    db.Column('films_film_id', db.Integer, db.ForeignKey('films.film_id')),
    db.Column('genres_genre_id', db.Integer, db.ForeignKey('genres.genre_id')))
all_films = Films.query.select_from(Films).join(films_genres).join(Genres).filter(
      (films_genres.c.films_film_id == Films.film_id) & (films_genres.c.genres_genre_id == Genres.genre_id))\
    .add_columns(
            Films.film_name,
            Genres.genre_name
            ).paginate()

当我提出请求时,我得到如下输出:

[(<Films 1>, 'The Shawshank Redemption', 'Action'), (<Films 1>, 'The Shawshank Redemption', 'Crime')] ...

如何重做查询以获得这种结果?

[(<Films 1>, 'The Shawshank Redemption', ('Action', 'Crime')]

或类似的东西,以便流派列表是一行,以便进一步将其转移到 flask_restx -> Resource -> json

4

0 回答 0