How to implement a search box for my website?

236 views
Skip to first unread message

Greg

unread,
Nov 3, 2007, 10:01:04 PM11/3/07
to Django users
Hello,
I've created a django website where I sell many different products,
that differ by color, manufacturer, size, price, shape, etc... I'm
wondering what the best way to implement a search box would be. I'd
want this search box to return only the products that relate to what
the user searches for.

I'd imagine I'll have to break the search terms up into a list. So if
the user searches for Red Aadi Sphinx. Then I'd put those words into
a list ['Red', 'Aadi', 'Sphinx']. And then take each one of the words
and search every class that I have in my models.py file and if I get
any matches then I'd append that to my search list.

Does anybody have any suggestions on how best to do this?

oliver

unread,
Nov 4, 2007, 5:58:42 AM11/4/07
to Django users
You probably want to use "Complex lookups with Q objects" (http://
www.djangoproject.com/documentation/db-api/)

here is how i use it on a site:
from django.db.models import Q

query = Q()
for term in request.GET['area'].split(' '):
q = Q(city__icontains = term) \
|Q(postcodeFirstPart__iexact = term) \
|Q(street1__icontains = term) \
|Q(street2__icontains = term) \
|Q(suburb__icontains = term) \
|Q(referenceID0__icontains = term) \
|Q(referenceID1__icontains = term)
query = query & q

(this is only one part of the bigger search query for a property
system)
"term" is the search term from you search box (called "area" here).

You can chain them up in OR & AND ..

finally you just call
object_list = Property.objects.all().filter(query, isLive=True)
with your query.

this should get you started ..

Reply all
Reply to author
Forward
0 new messages