Django レコード取得の基本① allメソッド getメソッド【Python】【初心者向け】

Django
この記事は約11分で読めます。

この記事の最終更新日: 2023年2月2日

レコードの取得と表示

前回は、管理者ツールからレコードの追加を行いました。

今回はレコードを全件取得し、表示するまでを解説していきます。

確認のために、あらかじめ適当なレコードを3件ほど入れておきましょう。

レコードの追加方法を忘れてしまった方は、以下の記事を参考にしてください。

それでは、views.pyurls.pyを以下のように編集してみましょう。

views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Customer

def index(request):
    data = Customer.objects.all()
    params = {
        'title':'DB_Practice',
        'message':'all data:',
        'data': data
    }
    return render(request, 'hello/index.html',params)

urls.py

from django.urls import path
from .views import index

urlpatterns = [
    path('', index, name='index'),
]

レコードを全件取得する、allメソッド

Customer.objects.all()とは

モデルクラスには「objects」という属性が用意されています。

objectsの「all」メソッドで、全てのレコードを取り出すことができます。

(レコード1行ごとにCustomerモデルのインスタンスが生成され、丸ごとセットで取得しています。)

allメソッドを使うだけで、全レコードの取得は完了してしまいます。非常に簡単です。

続いて、取得したレコードを表示してみましょう。

表示にはindex.htmlを編集する必要があります。

index.html

{% load static %}
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>{{title}}</title>
    </head>
    <body>
        <h1>{{title}}</h1>
        <table>
            <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>PREMIUM</th>
                <th>MAIL</th>
                <th>GENDER</th>
                <th>AGE</th>
                <th>BIRTHDAY</th>
            </tr>
    {%for item in data%}
            <tr>
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{% if item.flg_premium == False %}FALSE{% endif %}
                    {% if item.flg_premium == True %}TRUE{% endif %}
                </td>
                <td>{{item.mail_address}}</td>
                <td>{% if item.gender == 1 %}male{% endif %}
                    {% if item.gender == 2 %}female{% endif %}
                    {% if item.gender == 3 %}others{% endif %}
                </td>
                <td>{{item.age}}</td>
                <td>{{item.birthday}}</td>
            </tr>
    {% endfor %}
        </table>
    </body>
</html>

保存したら、以下のURLをブラウザに入力して画面を更新してみましょう。

すると、以下のような画面が表示されるはずです。

レコードが全件表示された画面

IDからレコードを検索する方法

次はレコード検索の基本について解説します。

最初に、サンプルコードからどのように実行するかを確認していきます。

IDで検索できるように、ID入力フォームを設置してみましょう。

編集するのはforms.py、index.html、views.pyの三つのファイルです。

forms.py

from django import forms

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

index.html

{% load static %}
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="utf-8">
        <title>{{title}}</title>
    </head>
    <body>
        <h1>{{title}}</h1>
        <table>
            <form action="{% url 'index' %}" method="post">
                {% csrf_token %}
                {{form.as_table}}
                <tr><td></td><td><input type="submit" value="click"></td></tr>
            </form>
        </table>
        <table>
            <tr>
                <th>ID</th>
                <th>NAME</th>
                <th>PREMIUM</th>
                <th>MAIL</th>
                <th>GENDER</th>
                <th>AGE</th>
                <th>BIRTHDAY</th>
            </tr>
    {%for item in data%}
            <tr>
                <td>{{item.id}}</td>
                <td>{{item.name}}</td>
                <td>{% if item.flg_premium == False %}FALSE{% endif %}
                    {% if item.flg_premium == True %}TRUE{% endif %}
                </td>
                <td>{{item.mail_address}}</td>
                <td>{% if item.gender == 1 %}male{% endif %}
                    {% if item.gender == 2 %}female{% endif %}
                    {% if item.gender == 3 %}others{% endif %}
                </td>
                <td>{{item.age}}</td>
                <td>{{item.birthday}}</td>
            </tr>
    {% endfor %}
        </table>
    </body>
</html>

views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Customer
from .forms import InputForm

def index(request):
    data = Customer.objects.all()
    params = {
        'title':'DB_Practice',
        'message':'all data:',
        'form':InputForm(),
        'data': [],
    }
    if (request.method == 'POST'):
        num=request.POST['id']
        item = Customer.objects.get(id=num)
        params['data'] = [item]
        params['form'] = InputForm(request.POST)
    else:
        params['data'] = Customer.objects.all
    return render(request, 'hello/index.html',params)

入力が完了すると、IDの入力フォームが表示され、以下のような画面になります。

確認できたら、IDを入力して「click」ボタンをクリックしてみましょう。

対象のレコードのみ表示されるはずです。

(存在しないIDを入力してしまうとエラーになるので注意してください。)

ID入力フォームが追加されている。

対象IDのレコードのみ表示される

IDを指定して取り出す、getメソッド

IDを指定して取り出すには、以下の2行のコードを覚えればOKです。

objects.get(id=num)
#フォームから取得したIDの値を、変数numに代入
num = request.POST['id']
#models.Modelを継承したクラスのobjects.getメソッドを使う。
#idとnumが一致したレコードを取得し、インスタンスを生成。→itemに代入している。
item = Customer.objects.get(id = num) 

以上、レコードの検索の基本の解説でした。

次回に続きます。

コメント

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