Section 9 database models
データを取得して、表示させる方法
テーブルを作るためにカタログパッケージの中にmodels.pyを設定する。 appフォルダーのdbをインポートする。
dev, test, prodのどのアプリのどのデータベースを使うかを決めなければならないのでwith文を使って明確にしておく。 dev.pyには接続先等のconfigが書かれている
これ出すには7ファイル
run.py /config/dev.py /app/__init__.py /app/catalog/__init__.py /app/catalog/models.py /app/catalog/routes.py /app/catalog/templates/hopme.html
run.py →サーバー起動
dev.py →データベース接続
/app/init.py →catalog.mainのapp起動
/app/catalog/models.py →データベースのテーブルからデータ取得
/app/catalog/routes.py →modelsからテーブル取得して、@main.route('/')で設定して、render_template('home.html', books=books)でデータ飛ばす
/app/catalog/templates/hopme.html →で表示する
ターミナル実行すると以下のようにデータベースから情報を取得して表示させることができる。
データベースの画像を表示させる方法
以下のように画像データを配置する。 home.htmlは以下のように追記する。
出版社ごとで絞って表示させる方法
home.htmlに以下を追記する。
<p><a href="">Publisher id:{{book.pub_id}}</a></p>
すると、hrefなのでurlが表示がされる。
次にフィルターの設定をする。
<>で値を渡すことができる。
pubulisher.htmlの設定をする。
<!DOCTYPE html> <html lang="en"> <head> <title> books inc </title> <meta charset="UTF-8"> </head> <body> <h4>Books by {{ publisher.name }}</h4> <ol> {% for book in publisher_books %} <li type="1"> {{ book.title }} by {{ book.author }} </li> {% endfor %} </ol> </body> </html>
home.htmlも追記する。href設定で2つのパラメーターを飛ばす。
href="{{url_for('main.display_publisher', publisher_id=book.pub_id)}}"
飛ばされるのは、この部分である。
①routeの名前
②次に引数を
まとめ
run.py→init.py→route.py→publisher.htmlの順で動く。
①route.pyで@main.route('/')を通常表示する。
②ここでpublisherをクリックすると、route.pyに絞り込みスクリプトが実行される
③home.htmlに<p><a href=
でURLを貼り付けてあるので次のページに飛ぶ
④publisher.htmlで②の絞込み処理をしたデータを表示する
*(route.pyではフィルター処理を行うコードとtemaplateに飛ばすコード)
@main.route('/display/publisher/<publisher_id>') def display_publisher(publisher_id): publisher = Publication.query.filter_by(id=publisher_id).first() publisher_books = Book.query.filter_by(pub_id=publisher.id).all() return render_template('publisher.html', publisher=publisher, publisher_books=publisher_books)
<p><a href="{{url_for('main.display_publisher', publisher_id=book.pub_id)}}">Publisher id:{{book.pub_id}}</a></p>
URLを押すと次のページに飛ばすように設定する。
次にIDをURLに表示させるようにする。
その下でも同じIDを渡す。
@main.route('/display/publisher/<publisher_id>')
loacalhost.5000/display/publisher/5
ここを5にしたら<publisher_id>も5になるので
順にfilter処理が始まる。
def display_publisher(publisher_id):
publisher = Publication.query.filter_by(id=publisher_id).first(
渡されたらIDで絞り込み処理を行う。
そしてブラウザに表示させる方法
ちなみに、publisher_booksを消すと本が取得できなくなる。
publisherで作者名を絞って、publisher_booksで本を全て表示している。