Commit | Line | Data |
---|---|---|
01b54c21 | 1 | import re |
2e4710d8 | 2 | from project.framonde.models import * |
01b54c21 MN |
3 | from django.shortcuts import render_to_response |
4 | from django.template import Context, RequestContext | |
5 | from django.db.models import Q | |
6 | from itertools import chain | |
7 | ||
8 | def normalize_query(query_string, | |
9 | findterms=re.compile(r'"([^"]+)"|(\S+)').findall, | |
10 | normspace=re.compile(r'\s{2,}').sub): | |
11 | return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] | |
12 | ||
13 | def get_query(query_string, search_fields): | |
14 | query = None # Query to search for every search term | |
15 | terms = normalize_query(query_string) | |
16 | for term in terms: | |
17 | or_query = None # Query to search for a given term in each field | |
18 | for field_name in search_fields: | |
19 | q = Q(**{"%s__icontains" % field_name: term}) | |
20 | if or_query is None: | |
21 | or_query = q | |
22 | else: | |
23 | or_query = or_query | q | |
24 | if query is None: | |
25 | query = or_query | |
26 | else: | |
27 | query = query & or_query | |
28 | return query | |
29 | ||
30 | def search(request): | |
31 | query_string = '' | |
32 | found_entries = None | |
33 | if ('q' in request.GET) and request.GET['q'].strip(): | |
34 | query_string = request.GET['q'] | |
35 | ||
36 | entry_query = get_query(query_string, ['titre', 'sous_titre', 'lieu', 'texte']) | |
37 | chercheC = Communication.objects.filter(entry_query).order_by('-date_pub') | |
38 | chercheCo = Contribution.objects.filter(entry_query).order_by('-date_pub') | |
39 | chercheO = Offre.objects.filter(entry_query).order_by('-date_pub') | |
40 | found_entries = chain(chercheC, chercheCo, chercheO) | |
41 | ||
42 | return render_to_response('search.html', | |
43 | { 'query_string': query_string, 'found_entries': found_entries }, | |
44 | context_instance=RequestContext(request)) |