[Answered ]-Search form in Django

1👍

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})

1👍

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})
👤Hybrid

Leave a comment