Djangoで簡単な検索機能を作ってみた


1.まず扱うデータテーブルを作る

・モデル

myapp/search/models.py

from django.db import models

class People(models.Model):
  name = models.CharField(max_length=20)
  def __str__(self):
      return self.name

・views.py

myapp/search/views.py

from django.shortcuts import render
from .models import People
from django.views.generic import ListView

class PeopleList(ListView):
    model = People

注)ここで使うtemplateの名前は自動でpeople_list.htmlとなる

・urls.py

myapp/search/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('', views.PeopleList.as_view(), name='people'),
]

・表示テンプレート

myapp/search/templates/search/people_list.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>people_list</title>
</head>
<body>
  <table border="1">
    <tr>
        <th>name</th>
    </tr>
    {% for people in object_list %}
    <tr>
        <td>{{ people.name }}</td>
    </tr>
    {% endfor %}
</table>
</body>
</html>

・出力結果

データはadmin画面から適当に登録する

2.検索機能を作る

models.py と urls.pyは変更なし

・views.py

myapp/search/views.py

from django.shortcuts import render
from .models import People
from django.views.generic import ListView


class PeopleList(ListView):
    def get_queryset(self):
        query = self.request.GET.get('query')

        if query:
            people_list = People.objects.filter(
                name__icontains=query)
        else:
            people_list = People.objects.all()
        return people_list

__containsは小文字大文字の区別がある
__icontainsは小文字大文字の区別がない
これらは、完全一致ではなく含まれるものを取得してくれる

・表示テンプレート

myapp/search/templates/search/people_list.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>people_list</title>
  </head>
  <body>

    <!-- formを追加 -->
    <form action="" method="get">
      <input name="query" value="{{ request.GET.query }}" type="text" />
      <button type="submit">検索する</button>
    </form>

    <table border="1">
      <tr>
        <th>name</th>
      </tr>
      {% for people in object_list %}
      <tr>
        <td>{{ people.name }}</td>
      </tr>
      {% endfor %}
    </table>
  </body>
</html>

request.GET.queryでURLのパラメータを取得している
つまり、http://127.0.0.1:8000/?query=<検索ワード>のようなパラメータを取得できる

・出力結果

しっかり検索出来ている
やったぁ

今回作ったもののgithub

参考元