python flask join two tables and show the result in html

Viewed 45
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://name:password@localhost/database'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


class Book(db.Model):
    __tablename__ = 'book'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(255))
    location = db.Column(db.String(55))
    series = db.relationship('Serie', backref='Serie', lazy='dynamic')


class Serie(db.Model):
    __tablename__ = 'serie'
    id = db.Column(db.Integer, primary_key=True)
    series_name = db.Column(db.String(55))
    book_id = db.Column(db.Integer, db.ForeignKey('book.id'))


@app.route('/')
def index():
    books = Book.query.join(Serie, Book.id == Serie.book_id).add_columns(Book.id, Book.title, Book.location, Serie.series_name)
    return render_template('bootstrap_table.html', title='Book Library',
                           book=books)


if __name__ == '__main__':
    app.run()

I can't seem to get the series_name to show up in place of the series when I render the html. Is the relationship to ForeignKey setup right? Or does the query need adjusting? This is the first time trying to use two tables.

I am using jinja {{book.title}}, {{book.location}}, {{Serie.series_name}} to get results in HTML. Notice series_name in place of series. I am trying to get Serie.series_name associated with the proper book.id in the 3rd column.

0 Answers
Related