A
A
aial2016-12-08 20:53:13
Flask
aial, 2016-12-08 20:53:13

How to display data from linked tables in Flask using the SQLAlchemy library?

How to pull data from related tables in Flask here is the model code

class Session_cinema(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    film_id = db.Column(db.Integer(), db.ForeignKey('film.id'))
    time = db.Column(db.DateTime)
    data = db.Column(db.DateTime)
    hall = db.Column(db.String(100))
    session_price = db.Column(db.Integer())

    def __init__(self, time, data, hall, session_price):
        self.time = time
        self.data = data
        self.hall = hall
        self.session_price = session_price
ForeignKey links this table to another table here is the code of this model
class Film(db.Model):
    id = db.Column(db.Integer(), primary_key = True)
    name = db.Column(db.String(80))
    description = db.Column(db.String(255))
    cast = db.Column(db.String(80))
    genre = db.Column(db.String(15))
    length = db.Column(db.Integer())
    ageRestriction = db.Column(db.Integer())

    def __init__(self, name, description,cast, genre, length, ageRestriction):
        self.name = name
        self.description = description
        self.cast = cast
        self.genre = genre
        self.length = length
        self.ageRestriction = ageRestriction
we need to display the data from the film table the name of the film. Here is the code that sends a list of data from the Session_cinema table
@app.route('/session/list', methods=['POST', 'GET'])
def session_list():
    return render_template('session_list.html', items=Session_cinema.query.all())
HTML
<tbody>
                        {% for item in items %}
                        <tr>
                            <td>{{ item.time }}</td>
                            <td>{{ item.data }}</td>
                            <td>{{ item.hall }}</td>
                            <td>{{ item.session_price }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
there before time should be the name of the movie.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2016-12-09
@aial

Define a relationship with Film in the Session_cinema model

class Session_cinema(db.Model):
    film_id = db.Column(db.Integer(), db.ForeignKey('film.id'))
    ...
    film = relationship('Film')

Then it will be possible to write in the template
<td>{{ item.film.name }}</td>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question