0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Djangoで、検索条件が入力されている場合のみ検索条件をセットする

Posted at

はじめに

Djangoを始めて5時間ほどなので、絶対もっといいやり方がある気がします。
ぜひ教えて下さい。
(一応このコードで動作はしている)

コード

views.py
from .models import Question
from .functions import add_filter

def list(request):
    filter_dict = {}
    add_filter(filter_dict, request, "question_text__icontains", "text")
    add_filter(filter_dict, request, "pub_date__gte", "date_from")
    add_filter(filter_dict, request, "pub_date__lte", "date_to")

    context = {
        "question_list": Question.objects.filter(**filter_dict)
    }

    return render(request, 'polls/list.html', context)
functions.py
# 検索条件があればセットし、空なら追加しない
def add_filter(filter_list, request, condition, value):
	if value not in request.POST:
		return

	filter_list[condition] = request.POST[value]

おわりに

引数4つも渡すのはちょっと嫌なんだけど、仕方ないかなということで諦める・・。
流石に馴染みのない言語のフレームワークを使うとなると四苦八苦ですが、新しい知識を吸収するのは楽しい

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?