user2719152
user2719152

Reputation: 989

How to write a django view to search in database?

i have been trying to make a search engine for my database(sqlite3). i have stored name of the places in the database. And i want to show an empty form to the user and get the input from that form and pass these as arguments to database_table.objects.filter() or by fetching all the rows from database and then searching these against these arguments. So my problem is how to write a view(either class based or function based) to achieve this functionality. I know how to query database but want to know how to write view for this. i am using Django-1.9 and python 3.4. I am struggling in it. Please help.

Upvotes: 0

Views: 5670

Answers (1)

geoom
geoom

Reputation: 8217

A Django's form isn't neccesary, a simple function-based view for searching might look like this:

views.py

from django.shortcuts import render

def search(request):

    template_name = 'search.html'

    query = request.GET.get('q', '')
    if query:
        # query example
        results = MyEntity.objects.filter(name__icontains=query).distinct()
    else:
        results = []
    return render(
        request, template_name, {'results': results})

take a look at basic tutorial from official django site

Upvotes: 1

Related Questions