Reputation: 477
I want to query my database for multiple conditions, like for instance I want to have a specific post from the foo author with the most comments. This query would be quite easy and straightforward, but I want that the user specifies the conditions. That means that I currently have a form like that one on my website:
Since the user is not pressured to set every condition there can be fields empty to search for. ( he doesn't select a hero for example ). I could now make an if statement for each condition to check if the user actually submitted one or not ( if request.POST.get('author')
) but that would be too much code I guess...
How did you guys approach such search forms in django? Any help or suggestion is highly appreciated!
Upvotes: 1
Views: 386
Reputation: 7049
You can use MODEL_NAME.objects.filter()
, and provide defaults.
And then, you can use __
to either go another level into relationships, or to run custom queries such as less than, greater than etc. (more info here: Django Querysets)
For example:
def get_hero(request):
if request.method == 'GET':
hero_name = request.GET.get('hero_name', 'DEFAULT_HERO')
guide_title = request.GET.get('guide_title', 'DEFAULT_TITLE')
heros = Hero.objects.filter(hero__name=hero_name, guide__title=guide_title)
return render(request, 'template.html', {'heros': heros})
Upvotes: 1
Reputation: 3838
Filter a Django queryset. Querysets are chainable, so you can apply successive filters based on the conditions specified by the user. Having if
statements for four conditions doesn't seem too excessive:
def search_view(request):
results = Guide.objects.all()
title = request.POST.get('title')
if title:
results = results.filter(title__icontains=title)
# other conditions...
hero = request.POST.get('hero', 'all')
if hero != 'all':
results = results.filter(hero=hero)
render_to_response('search_results.html', {'results': results})
Upvotes: 1