【17/8/29】副業14日目

Ryo Uehara
Aug 29, 2017 · 5 min read

前回は検索ワードを検索ページに引き渡す部分を実装した。
今日は通勤中に調べたCSRFと検索ワードからDBのフィルタをかけて取得する部分を作っていく。

CSRFの実装

HTML側には以下を記載する。

<form action=”/search” method=”post”>
 {% csrf_token %}
  <input type=”search” name=”search” placeholder=”キーワードを入力してください”>
  <input type=”image” src=”{% static ‘img/btn_search.png’ %}” name=”submit” alt=”検索”>
</form>

View側にも@csrf_protectを記載して、RequestContextを使う必要があるのだが、エラーが発生しなかった。。。?
エラーが発生したときに考えよう。

検索ワードでDBから検索

以下のサイトがDjangoのModelとSQLの書き方を比較していてわかりやすい。

タグDBの中が、[id]-[name]-[site_id]となっているから、name列で検索してsite_idの結合したDBを作って、それを抽出すればよいのか?
まずは、DBの結合方法を調べる。以下サイトがわかりやすい。

上記を踏まえると以下のSelect文となる。

SELECT * FROM t_site_tag LEFT JOIN t_site ON t_site_tag.site_id_id = t_site.id

サイトタグテーブルから全てのカラムを取得し、それに、サイトタグテーブルのsite_idとサイトテーブルのidを対応させた状態で、サイトテーブルをひっつけてあげてくださいという意味になる。

この*の部分を取得したカラムを指定する。

SELECT t_site.id,t_site.name,t_site.created_at FROM t_site_tag LEFT JOIN t_site ON t_site_tag.site_id_id = t_site.id

その上で、サイトテーブルで取得したデータとマージして、重複排除すれば純粋な検索結果となるのかな???(半信半疑。。)

今日は時間がないので、実際の実装は次回に回す。

検索ワードのlist化処理

TOPページの検索窓で入力した検索ワードをスペース区切りで個別のセンテンスに分ける処理を入れた。

def search(request):
if request.method == ‘POST’:
print(“Method is POST”)
search_word = request.POST[“search”].split()
context = {
# “search” : request.POST[“search”]
“search_words” : search_word
}
return render(request, ‘search.html’, context)
else:
print(“Method is GET”)
return render(request, ‘search.html’)

次回は、search_word(リスト)を使って、DBの検索機能を実装する。
以下サイトが参考になりそう。明示的にLEFT・RIGHTを指定するのではなくModelのつくりによってLEFT JOINなのかRIGHT JOINかが決まる模様。。。

続く。


備忘録:紙に書いたDB設計を貼っておく。

365日備忘録

Full Stack Engineerを目指して

)
    Ryo Uehara

    Written by

    365日備忘録

    Full Stack Engineerを目指して

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade