.:: adilbenseddik's blog of humor and code ::.

Searching with django

Implementation of Julien Philap approach to searching.

2014-12-04 django, python, search

Not very happy with django full text __search option with mysql myisam storage engine I end up using Julien Philap approach to searching. Finding a proper way to implement it in my project was not easy for a django beginner like me, but thanks to Ronaldo Bahia answer on stackoverflow I managed to proceed.

Therefore, here is the code that might help..


# views.py
def normalize_query(query_string,
    findterms=re.compile(r'"([^"]+)"|(\S+)').findall,
    normspace=re.compile(r'\s{2,}').sub):
    return [normspace('',(t[0] or t[1]).strip()) for t in findterms(query_string)]

def get_query(query_string, search_fields):
    query = None
    terms = normalize_query(query_string)
    for term in terms:
        or_query = None
        for field_name in search_fields:
            q = Q(**{"%s__icontains" % field_name: term})
            if or_query is None:
                or_query = q
            else:
                or_query = or_query | q
        if query is None:
            query = or_query
        else:
            query = query & or_query
    return query

def search_for_something(request):
    query_string = ''
    found_entries = None
    if ('q' in request.GET) and request.GET['q'].strip():
        query_string = request.GET['q']
        entry_query = get_query(query_string, ['field1', 'field2', 'field3']) # your search fields
        found_entries = Model.objects.filter(entry_query).order_by('-something') # your model

    return render_to_response('app/template-result.html',
            { 'query_string': query_string, 'found_entries': found_entries },
            context_instance=RequestContext(request)
        )
# search.html
<form class="" method="get" action="{% url 'search_for_something' %}">
    <input name="q" type="text" />
    <button type="submit">Search</button>
</form>

# results.html
{% if found_entries %}
   {% for model in found_entries %} # your model
        {{ model.field }} # your model fields
   {% endfor %}
{% endif %}
# urls.py
url(r'^results/$', 'yourapp.views.search_for_something', name='search_for_something'),


Freelance, Full-stack

As a child, i learned how to write code because i figured one day this internet thing would help me share my art and knowledge with nice people all over the world. Back then i would draw images on corky image manipulation programs, make bad paintings, memorize defunct 1930s and 1960s architecture books, and take pictures of neighborhood dolls with my mom's camera.
Since then, i've been to some nice schools, learned many computer skills, painted things that aren't strong bloodthirsty barbarians, lived in 3 countries, worked few years for major companies, founded another one to become a photographer, advised one minister at moroccan government, and worked independently for a couple more (and counting)..


twitter/adilbenseddik
github/adilbenseddik


Portfolio available on request:


Code, design and content by
adil.benseddik@mabcs.com
+33(0)611632168
11 Avenue de Taillebourg, 75011 Paris


Copyright ©2014