Djangoで作成したデータベース内の全レコードを取得し表示する方法をご紹介します。
[toc]
ビューの作成
ビューを使って、データベースのレコードを取得してみます。
views.py
from django.shortcuts import render from .models import Friend def index(request): data = Friend.objects.all() params = { 'title': 'Hello', 'massage': 'all friends', 'data': data, } return render(request, 'hello/index.html', params)
models.pyにあるFriendクラスをインポートし、Friend.objects.all()で全てのレコードを取得します。
テンプレートの作成
テンプレートを使って取得したオブジェクトを表示します。
index.html
<table> <tr> <th>ID</th> <th>NAME</th> <th>GENDER</th> <th>MAIL</th> <th>AGE</th> <th>BIRTHDAY</th> </tr> {% for item in data %} <tr> <td>{{ item.id }}</td> <td>{{ item.name }}</td> <td>{% if item.gender == False %}male{% endif %} {% if item.gender == True %}female{% endif %}</td> <td>{{ item.mail }}</td> <td>{{ item.age }}</td> <td>{{ item.birthday}}</td> <tr> {% endfor %} </table>
テンプレートタグであるfor文を使って、全レコードをTable形式で出力します。genderはbooleanで定義されているので、Falseであれば男性、Trueであれば女性と判定します。
実行結果
サーバにアクセスすると全てのレコードが表示されます。

以上です。皆さんの学習の手助けになれば嬉しいです。