LoginSignup
0
3

More than 1 year has passed since last update.

Flaskのログイン機能を作ったので、追加機能で
検索機能も作ってみました!
CRUD+ログイン機能の記事はこちらになります🙇

コード

app.py
@app.route('/tweets')
def index():
-     tweets = Tweet.query.all()
+     text_input = request.args.get('search')
+     if text_input is None or len(text_input) == 0:
+         tweets = Tweet.query.all()
+     else:
+         tweets = db.session.query(Tweet).filter(or_(Tweet.body.like(text_input), Tweet.title.like(text_input))).all()
    return render_template('index.html', tweets=tweets)

変更箇所は以前のものが赤、新しい箇所は緑です!

index.html
{% extends "application.html" %}
{% block content %}
+    <div class="search">
+        <form>
+            <input type="text" name="search">
+            <input type="submit" value="検索">
+        </form>
+    </div>
    <div class="tweets_container">
        <h3>投稿一覧</h3>
        {% for tweet in tweets %}
        <div class="tweet">
            <div class="main_box">
                <div class="left_container">
                    <p><b>{{tweet.title}}</b> {{tweet.body}}</p>
                </div>
                <div class="right_container">
                    <a href="/tweets/{{tweet.id}}">詳細</a>
                    {% if tweet.user_id == current_user.id %}
                        <a href="/tweets/{{tweet.id}}/edit">編集</a>
                        <a href="/tweets/{{tweet.id}}/delete">削除</a>
                    {% endif %}
                </div>
            </div>
            <p class="time">{{ tweet.created_at }}</p>
        </div>
        {% endfor %}
    </div>

{% endblock %}

ざっとこんな感じです!
以下に解説を続けます!

クエリパラメータ

今回の検索機能は、クエリパラメータ(URLのとこに出てくる文字列)を利用して
実装しています。URLの例は[baseURL]/tweets?search=aaaの形式で
request.args.get(パラメータ名)で取得できます!
htmlでは、name属性にパラメータ名を入れるだけでOKです!
<input type="text" name="search">

検索のロジック

app.py
if text_input is None or len(text_input) == 0:
    tweets = Tweet.query.all()
else:
    tweets = db.session.query(Tweet).filter(or_(Tweet.body.like(text_input), Tweet.title.like(text_input))).all()

条件分岐

検索の入力欄がNone(最初にページ遷移した場合)
or文字が入っていない時(文字列長0)に全ての投稿を取得し、
検索の入力欄に何かしら入っているときは、検索を行います👏

query

db.session.query(Tweet).filter(or_(Tweet.body.like(text_input), Tweet.title.like(text_input))).all()
クエリを請求するステートメントですが、Tweetクラス(Tweetテーブル)に
関するクエリ(query(Tweet))でフィルターをかけます。
filterの条件は、Tweetテーブルのカラムbodyまたはtitle
検索する文字が含まれているものを取得するものです🙌

他の条件は以下の記事が参考になると思います!

参考文献

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3