2 from framonde
.models
import *
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
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
)]
13 def get_query(query_string
, search_fields
):
14 query
= None # Query to search for every search term
15 terms
= normalize_query(query_string
)
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
})
23 or_query
= or_query | q
27 query
= query
& or_query
33 if ('q' in request
.GET
) and request
.GET
['q'].strip():
34 query_string
= request
.GET
['q']
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
)
42 return render_to_response('search.html',
43 { 'query_string': query_string
, 'found_entries': found_entries
},
44 context_instance
=RequestContext(request
))