Djangoを勉強してみる_モデルを学ぶ_その2(入門編)

django-339744_640.png Django

前回の続きで、Djangoについて学んでいきます。

今回からモデルについて勉強していきます。

Djangoの勉強内容は以下の本を参考にしています。

参考

Python Django3超入門 (日本語) 単行本 – 2020/6/13 掌田 津耶乃 (著)

モデル

コードは以前の記事を参考にしてください。

Djangoを勉強してみる(入門編)
Djangoを勉強してみる(入門編その2)
Djangoを勉強してみる_urlを学ぶ(入門編)
Djangoを勉強してみる_テンプレートを学ぶ(入門編)
Djangoを勉強してみる_テンプレートを学ぶ_その2(入門編)
Djangoを勉強してみる_フォームを学ぶ_その1(入門編)
Djangoを勉強してみる_フォームを学ぶ_その2(入門編)
Djangoを勉強してみる_フォームを学ぶ_その3(入門編)
Djangoを勉強してみる_モデルを学ぶ_その1(入門編)

今回の目的

前回はモデルを作ってデータベースにサンプルデータを作成するところまでやりました。
今回は作成したデータベースにDjangoのアプリケーションからデータの取得について勉強していきます。

ではさっそく作っていきます。

データを表示する(全体)

まずは、すべてのデータを取り出して表示してみます。

データを取り出すためにviews.pyを編集します。

1.views.pyを編集

ファイル:sample_app>hello>models.py

コード:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Friend #追加

def index(request):
    data = Friend.objects.all() #追加
    params = {
        'title': 'Hello World!!',
        'msg': 'これはサンプルページです。',
        'data': data, #追加
    }
    return render(request, 'hello/index.html', params)

このコードでは、モデルのFriendクラスをimportしています。

そして、すべてのデータを取り出すときに以下のようにします。

data = Friend.objects.all()

あとは、params変数にその変数を定義しています。

次にテンプレートに表示させる処理を書きます。

2.index.htmlを編集

ファイル:sample_app>hello>templates>hello>index.html

コード:

<!DOCTYPE html>
<html lang="ja">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">

    <title>{{ title }}</title>
</head>
<body class = "container">
    <h1>{{ title }}</h1>
    <p>{{ msg|safe }}</p>
    <table class="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>
</body>
</html>

このコードでは、モデルで定義したデータをテーブルを作り、繰り返し分のfor文を使って取り出しています。

{% for item in data %}

データベースの各項目を取り出す場合は、「for文の変数.モデルの変数」で取り出すことができます。

また、条件式のif文を使って条件に応じて表示する文字を変更したりすることもできます。

{% if item.gender == False %}male{% endif %} 
{% if item.gender == True %}female{% endif %}

以上で設定が終わったので、動作確認してみます。

動作確認

python manage.py runserver

ブラウザで以下にアクセスします。

http://localhost:8000/hello

そうすると次のようにデータベースの中身を一覧で表示することができます。

 

データを表示する(特定のID)

次は特定のIDを取り出すようにしてみます。

特定のIDを入れるためのフォームを準備するためforms.pyを編集します。

1.forms.pyを編集

ファイル:sample_app>hello>forms.py

コード:

from django import forms

class HelloForm(forms.Form):
    id = forms.IntegerField(label='ID')

まずはIDをフォームに準備します。

続いてテンプレートに表示します。

2.index.htmlを編集

ファイル:sample_app>hello>templates>hello>index.html

コード:

<!DOCTYPE html>
<html lang="ja">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">

    <title>{{ title }}</title>
</head>
<body class = "container">
    <h1>{{ title }}</h1>
    <p>{{ msg|safe }}</p>
#ここから追加--- <form action="{% url 'index' %}" method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="click"> </form>
#ここまで----- <table class="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> </body> </html>

検索するためにテキストフォームとクリックボタンを準備しています。

最後にviews.pyを修正します。

3.views.pyを編集

ファイル:sample_app>hello>views.py

コード:

from django.shortcuts import render
from django.http import HttpResponse
from .models import Friend
from .forms import HelloForm

def index(request):
    params = {
        'title': 'Hello World!!',
        'msg': 'ALL Friends',
        'data': [],
        'form': HelloForm(),
    }
    if (request.method == 'POST'):
        num = request.POST['id']
        item = Friend.objects.get(id=num)
        params['data'] = [item]
        params['form'] = HelloForm(request.POST)
    else:
        params['data'] = Friend.objects.all()
    return render(request, 'hello/index.html', params)

このコードではテンプレートからPOSTデータがあるか無いかによって処理を変えるようにしています。

if (request.method == 'POST'):

もし、POSTのデータが送られてきた場合は、num変数にフォームで送られてきたIDを代入しています。

その後、item変数にデータベースのIDとPOSTで送られてきたIDが一致するものを代入しています。

item変数に代入した値を、paramas辞書のdataというキーに代入しています。

最後にフォームのデータを上書きするための処理を書いています。

逆にPOSTデータが無い場合は、すべてのデータをparamas辞書のdataというキーに代入しています。

これで完了したので動作を見てみます。
※サンプルデータの2つ目を準備しました。

ID:2
NAME:テストデータ2
GENDER:male
MAIL:test2@hoge.co.jp
AGE:20
BIRTHDAY:2020-7-14

ページを表示したら、フォームに「2」を入れてクリックします。

 

ちゃんとIDが2だけの項目が抽出できました。

今回の目的であるDjangoのアプリケーションからデータの取得することができました。

次回はデータの登録について勉強していこうと思います。

以上です。ありがとうございました。

P.S.

勉強を継続することが苦手ですか?

少し前からココナラというサービスで習慣化のテクニックについて教えるサービスを始めました。

もし、いつも3日坊主で終わってしまうという方や、ダイエットを続けたい、勉強したい、運動したいなど何か習慣化したいと思っている方がいましたら全力でサポートしますので、まずは覗いてみてください。

すでに何人かの方に実践してもらって効果が出ているという感想をいただいてます。

人生変わる?【習慣化の方法】を教えます 【残り1名】ダイエット、勉強、運動を続けることが苦手ですか?

コメント

タイトルとURLをコピーしました