Simple Django search

Skip to first unread message

Maciej Bliziński

Jun 6, 2007, 6:05:38 AM6/6/07
to Django users
Hi Djangoers!

I've been interested in a search feature in Django for some time now.
I did some research lately and found the following posts about it:

* Search Functionality
* Search options
* How to integrate a search engine in a Django site?
* Search feature

I've found that all of those solutions require some additional
software (such as Lucene, for instance). I was thinking about
something that would be pure Django/Python code, that would work like

I've recently written the simplest code I could, to do the job: index
objects and then allow to search them, returning their titles and
absolute URLs. I've tried to make it as general as possible. My
implementation is inspired (or stolen from ;-) )
django.contrib.comments. It can index any class of objects. Classes to
be indexed need to implement two methods: get_search_text() and

Here's an example code for indexing objects:

from myapp.models import MyClass
from import Keyword
from django.contrib.contenttypes.models import ContentType

ct = ContentType.objects.get_for_model(MyClass)
object_id = 1
Keyword.objects.index_object(ct, object_id)

...and for searching:

from import KeywordManager
from django.contrib.contenttypes.models import ContentType
from myapp.models import MyClass
ct = ContentType.objects.get_for_model(MyClass)
km = KeywordManager()
result =, "Monty Python")
print result

[{'url': '/path/object/',
'preview': 'preview of the object content',
'title': 'Object title' },
{ ... }, ... ]

Results are a list of dictionaries where each dictionary has fields:
url, preview and title.

The code is available from:

This is very immature code which I've put together last few days, but
it does the job and I think it could be useful for other people too.

It's biggest strength is that it's enough to put few files into the
django/contrib directory and run syncdb -- it's ready to go.

All comments are very welcome!

Maciej Bliziński

Reply all
Reply to author
0 new messages