本文整理汇总了Python中haystack.query.EmptySearchQuerySet类的典型用法代码示例。如果您正苦于以下问题:Python EmptySearchQuerySet类的具体用法?Python EmptySearchQuerySet怎么用?Python EmptySearchQuerySet使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了EmptySearchQuerySet类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: personal_search
def personal_search(request):
"""
The user can search any item within his own collections and can search **only shared items** of other users
TODO: Build a hash table to store item_id in the result of user_item to reduce time from O(n^2) to O(n)
Reference: http://docs.haystacksearch.org/dev/searchqueryset_api.html#field-lookups
"""
#Two parameters to tune
RESULTS_PER_PAGE = 10
load_all = False
query = request.GET['q'].strip() #Heystack only accepts key name as 'q'
user_id = int(request.GET['pid'])
if query == '':
sqs = EmptySearchQuerySet()
else:
searchqueryset = SearchQuerySet()
if user_id == request.user.pk:
pronoun = '我'
own_items = User_Item.objects.filter(user__pk=request.user.pk)
else:
pronoun = Profile.objects.get(pk=user_id).name
own_items = User_Item.objects.filter(user__pk=user_id).exclude(status=1)
own_items_ids = []
for oi in own_items:
own_items_ids.append(int(oi.item_id))
sqs = searchqueryset.auto_query(query).filter(primary_key__in=own_items_ids)
if load_all:
sqs = sqs.load_all()
paginator = Paginator(sqs, RESULTS_PER_PAGE)
try:
page = paginator.page(request.GET.get('page', 1))
feeds_id = ''
for result in page.object_list:
feeds_id += str(result.object.id) + ','
feeds_id = feeds_id[:-1]
topics_of_item_dict = get_topics_of_item(feeds_id, request.user.pk)
friends_of_item_dict = get_friends_of_item(feeds_id, request.user.pk)
user_item_status_dict = get_user_items(feeds_id, request.user.pk)
except InvalidPage:
raise Http404
context = {
'query': query,
'page': page,
'page_type':'search',
'topics_of_item_dict':topics_of_item_dict,
'friends_of_item_dict':friends_of_item_dict,
'user_item_status_dict':user_item_status_dict,
'paginator': paginator,
'suggestion': None,
'pronoun': pronoun,
'num_results': len(sqs),
'user_id': user_id
}
from django.template import add_to_builtins
add_to_builtins('haystack.templatetags.highlight')
return render_to_response('main/search/personal_search_results.html', context, context_instance=RequestContext(request))
示例2: EmptySearchQuerySetTestCase
class EmptySearchQuerySetTestCase(TestCase):
def setUp(self):
super(EmptySearchQuerySetTestCase, self).setUp()
self.esqs = EmptySearchQuerySet()
def test_get_count(self):
self.assertEqual(self.esqs.count(), 0)
self.assertEqual(len(self.esqs.all()), 0)
def test_filter(self):
sqs = self.esqs.filter(content='foo')
self.assert_(isinstance(sqs, EmptySearchQuerySet))
self.assertEqual(len(sqs), 0)
def test_exclude(self):
sqs = self.esqs.exclude(content='foo')
self.assert_(isinstance(sqs, EmptySearchQuerySet))
self.assertEqual(len(sqs), 0)
def test_slice(self):
sqs = self.esqs.filter(content='foo')
self.assert_(isinstance(sqs, EmptySearchQuerySet))
self.assertEqual(len(sqs), 0)
self.assertEqual(sqs[:10], [])
try:
sqs[4]
self.fail()
except IndexError:
pass
示例3: search
def search(request):
"""
Modification/Combination based on two haystack classes:
1,haystack/views/SearchView
2,haystack/forms/SearchForm/search()
Reference:
#. http://docs.haystacksearch.org/dev/
#. http://lucene.apache.org/solr/tutorial.html
"""
#Two parameters to tune
RESULTS_PER_PAGE = 10
load_all = False
query = request.GET['q'].strip() #Heystack only accepts key name as 'q'
if query == '':
sqs = EmptySearchQuerySet()
else:
searchqueryset = SearchQuerySet()
sqs = searchqueryset.auto_query(query) #The default auto_query method has been modified to use OR instead of AND
if load_all:
sqs = sqs.load_all()
paginator = Paginator(sqs, RESULTS_PER_PAGE)
try:
page = paginator.page(request.GET.get('page', 1))
feeds_id = ''
for result in page.object_list:
feeds_id += str(result.object.id) + ',' #If an item is deleted and not reindexed, then error
feeds_id = feeds_id[:-1]
topics_of_item_dict = get_topics_of_item(feeds_id, request.user.pk)
friends_of_item_dict = get_friends_of_item(feeds_id, request.user.pk)
user_item_status_dict = get_user_items(feeds_id, request.user.pk)
except InvalidPage:
raise Http404
context = {
'query': query,
'page': page,
'page_type':'search',
'topics_of_item_dict':topics_of_item_dict,
'friends_of_item_dict':friends_of_item_dict,
'user_item_status_dict':user_item_status_dict,
'paginator': paginator,
'suggestion': None,
'num_results': len(sqs),
}
from django.template import add_to_builtins
add_to_builtins('haystack.templatetags.highlight') #Changed haystack.utils.Highlighter.highliht to not use window
return render_to_response('main/search/web_search_results.html', context, context_instance=RequestContext(request))
示例4: get
def get(self, request, fmt=None):
context = {}
if fmt:
query = ''
results = EmptySearchQuerySet()
form = self.form_class(request.GET, searchqueryset=self.searchqueryset, load_all=True)
if form.is_valid():
print form.cleaned_data
query = form.cleaned_data['q']
order_by = request.GET.get('order_by', None)
results = form.search(order_by)
else:
results = form.no_query_found()
if self.facets:
for facet in self.facets:
results = results.facet(facet[0], mincount=1, sort=facet[1])
context['facets'] = results.facet_counts()
paginator = Paginator(results, 25)
page = request.GET.get('page', '1')
try:
content = paginator.page(page)
except PageNotAnInteger:
content = paginator.page(1)
except EmptyPage:
content = paginator.page(paginator.num_pages)
context['content'] = content
context['paginator'] = paginator
context['query'] = query
context['form'] = form
return self.render_to_format(request, context, self.template_name, fmt)
else:
params = []
if not request.GET.get('q') and not request.GET.get('order_by'):
params.append('order_by={}'.format(self.default_order))
for param in self.params:
print param['name']
param_value = request.GET.get(param['name'], param['default'])
if param_value:
params.append('{}={}'.format(param['name'], param_value))
print params
context['params'] = '&'.join(params)
context['status_code'] = 303
context['additional_headers'] = {'location': self.path}
context['content'] = None
return self.render(request, context, self.template_name)
示例5: EmptySearchQuerySetTestCase
class EmptySearchQuerySetTestCase(TestCase):
def setUp(self):
super(EmptySearchQuerySetTestCase, self).setUp()
self.esqs = EmptySearchQuerySet()
def test_get_count(self):
self.assertEqual(self.esqs.count(), 0)
self.assertEqual(len(self.esqs.all()), 0)
def test_filter(self):
sqs = self.esqs.filter(content='foo')
self.assert_(isinstance(sqs, EmptySearchQuerySet))
self.assertEqual(len(sqs), 0)
def test_exclude(self):
sqs = self.esqs.exclude(content='foo')
self.assert_(isinstance(sqs, EmptySearchQuerySet))
self.assertEqual(len(sqs), 0)
示例6: EmptySearchQuerySetTestCase
class EmptySearchQuerySetTestCase(TestCase):
def setUp(self):
super(EmptySearchQuerySetTestCase, self).setUp()
self.esqs = EmptySearchQuerySet()
def test_get_count(self):
self.assertEqual(self.esqs.count(), 0)
self.assertEqual(len(self.esqs.all()), 0)
def test_filter(self):
sqs = self.esqs.filter(content="foo")
self.assertTrue(isinstance(sqs, EmptySearchQuerySet))
self.assertEqual(len(sqs), 0)
def test_exclude(self):
sqs = self.esqs.exclude(content="foo")
self.assertTrue(isinstance(sqs, EmptySearchQuerySet))
self.assertEqual(len(sqs), 0)
def test_slice(self):
sqs = self.esqs.filter(content="foo")
self.assertTrue(isinstance(sqs, EmptySearchQuerySet))
self.assertEqual(len(sqs), 0)
self.assertEqual(sqs[:10], [])
try:
sqs[4]
self.fail()
except IndexError:
pass
def test_dictionary_lookup(self):
"""
Ensure doing a dictionary lookup raises a TypeError so
EmptySearchQuerySets can be used in templates.
"""
self.assertRaises(TypeError, lambda: self.esqs["count"])
示例7: setUp
def setUp(self):
super(EmptySearchQuerySetTestCase, self).setUp()
self.esqs = EmptySearchQuerySet()
示例8: basic_search
def basic_search(request, template='search/search.html', load_all=True, form_class=ModelSearchForm, searchqueryset=None, context_class=RequestContext, extra_context=None, results_per_page=None, sort_by=[]):
"""
A more traditional view that also demonstrate an alternative
way to use Haystack.
Useful as an example of for basing heavily custom views off of.
Also has the benefit of thread-safety, which the ``SearchView`` class may
not be.
Template:: ``search/search.html``
Context::
* form
An instance of the ``form_class``. (default: ``ModelSearchForm``)
* page
The current page of search results.
* paginator
A paginator instance for the results.
* query
The query received by the form.
"""
query = ''
results = EmptySearchQuerySet()
try:
del request.session['selected_facets']
except:
pass
if request.GET.get('q'):
form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all)
if form.is_valid():
query = form.cleaned_data['q']
results = form.search()
else:
form = form_class(searchqueryset=searchqueryset, load_all=load_all)
results = SearchQuerySet().all()
selected_facets = request.GET.getlist('selected_facets')
selected_date_facets = request.GET.getlist('selected_date_facets')
selected_facets = FacetSet(facet_string_list=selected_facets,
date_facet_string_list=selected_date_facets)
request.session['selected_facets'] = selected_facets
results = selected_facets.narrow(results)
if not sort_by == ['tmp']:
results = results.order_by(*sort_by)
results = results.order_by('-score')
if not template:
return results
count = results.count()
paginator = Paginator(results, results_per_page or RESULTS_PER_PAGE)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("No such page of results!")
context = {
'form': form,
'page': page,
'paginator': paginator,
'query': query,
'suggestion': None,
'count': count,
}
if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False):
context['suggestion'] = form.get_suggestion()
if extra_context:
context.update(extra_context)
return render_to_response(template, context, context_instance=context_class(request))
示例9: search
def search(request, template='search/search.html', load_all=True,
form_class=ModelSearchForm, searchqueryset=None,
extra_context=None,
results_per_page=None):
"""
"""
context = RequestContext(request)
query = ''
results = EmptySearchQuerySet()
if request.GET.get('q'):
form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all)
if form.is_valid():
query = form.cleaned_data['q']
results = form.search()
context.update({'last_search': query})
# if return no result, try it again with autocomplete search word
if results.count() == 0:
results = SearchQuerySet().autocomplete(enfname=request.GET.get('q', ''))
else:
form = form_class(searchqueryset=searchqueryset, load_all=load_all)
selected_facets_list = []
if request.GET.getlist('selected_facets'):
for facet in request.GET.getlist('selected_facets'):
if ":" not in facet:
continue
field, value = facet.split(":", 1)
results = results.narrow(u'%s:"%s"' % (field, value))
# 生成页面的facet
selected_facets_list.append(('&selected_facets='+facet, value))
selected_facets_context = list({
'name': i[1],
'rm_selected_facet': ''.join(list(j[0] for j in selected_facets_list if j!=i))}
for i in selected_facets_list)
context.update({'selected_facets_context': selected_facets_context})
def facet_field_to_selector(sqs, name, context_name):
try:
fields = sqs.facet(name).facet_counts()['fields'][name]
return {'name': context_name,
'exact_name': name,
'options': list({'context': i} for i in fields)}
except:
pass
return None
selectors = []
# 找出品牌的facet
selectors.append(facet_field_to_selector(results, 'brand', '品牌'))
# 找出品类的facet
selectors.append(facet_field_to_selector(results, 'categ', '品类'))
context.update({'selectors': selectors})
rm_invalid_result = []
for r in results:
try:
tmp = r._get_object()
if tmp:
rm_invalid_result.append(tmp)
except:
pass
paginator = HXPaginator(rm_invalid_result, results_per_page or 40)
page = int(request.GET.get('page', 1))
try:
templates = paginator.page(page)
except PageNotAnInteger:
page = 1
except EmptyPage:
page = paginator.num_pages
context.update({
'form': form,
'templates': templates,
'paginator': paginator,
'query': query,
'suggestion': None,
})
if results.query.backend.include_spelling:
context['suggestion'] = form.get_suggestion()
if extra_context:
context.update(extra_context)
return TemplateResponse(request, template, context)
示例10: catalogue_search
def catalogue_search(request, template='search/search.html', load_all=True,
form_class=CatalogueSearchForm, searchqueryset=None, extra_context=None,
results_per_page=None):
"""
A more traditional view that also demonstrate an alternative
way to use Haystack.
Useful as an example of for basing heavily custom views off of.
Also has the benefit of thread-safety, which the ``SearchView`` class may
not be.
Template:: ``search/search.html``
Context::
* form
An instance of the ``form_class``. (default: ``ModelSearchForm``)
* page
The current page of search results.
* paginator
A paginator instance for the results.
* query
The query received by the form.
"""
query = ''
results = EmptySearchQuerySet()
results_per_page = results_per_page or RESULTS_PER_PAGE
if request.GET.get('q'):
form = form_class(request.GET, searchqueryset=searchqueryset, load_all=load_all)
if form.is_valid():
query = form.cleaned_data['q']
results = form.search()
else:
form = form_class(searchqueryset=searchqueryset, load_all=load_all)
results = results.facet('categories').facet('country').facet('has_images').facet('global_region').facet('item_name')
if form.is_valid():
results = filter_with_facet(form, results, 'item_name', 'item_name')
results = filter_with_facet(form, results, 'category', 'categories')
results = filter_with_facet(form, results, 'global_region', 'global_region')
results = filter_with_facet(form, results, 'country', 'country')
if form.cleaned_data['person']:
sqs = SearchQuerySet()
for p in form.cleaned_data['person'].split():
term = sqs.query.clean(p)
results = results.narrow(u'people:"%s"' % term)
if form.cleaned_data['has_images'] == True:
results = results.narrow(u'has_images_exact:true')
facets = results.facet_counts()
if facets:
# Prepare the form with all the available facets
load_facets_into_form(form, facets, 'item_name', 'item_name')
load_facets_into_form(form, facets, 'category', 'categories')
load_facets_into_form(form, facets, 'global_region', 'global_region')
load_facets_into_form(form, facets, 'country', 'country')
# Append count of images into form
appended_count = False
for name, val in facets['fields']['has_images']:
if name == 'true':
form.fields['has_images'].label += ' (%s)' % val
appended_count = True
if not appended_count:
form.fields['has_images'].label += ' (0)'
results = results.order_by('registration_number')
paginator = Paginator(results, results_per_page)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
raise Http404("No such page of results!")
context = {
'form': form,
'page': page,
'paginator': paginator,
'query': query,
'suggestion': None,
'facets': facets,
}
# Store query for paging through results on item detail page
if form.is_valid():
request.session['search_query'] = form.cleaned_data
# Access the first result to prevent ZeroDivisionError
if results:
results[0]
request.session['search_results'] = results
request.session['search_results_per_page'] = results_per_page
if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False):
context['suggestion'] = form.get_suggestion()
#.........这里部分代码省略.........
示例11: search
def search(request):
"""
Description: Handles requests from site's search bar
Based off haystack.views.basic_search()
Arguments: request: HttpRequest object
Return: HttpResponse object showing search results with following
additional details
- query: search query
- suggestion: backend-suggested search query
Author: Nnoduka Eruchalu
"""
query = ""
results = EmptySearchQuerySet()
suggestion = False
if request.GET.get("q"):
form = SearchForm(request.GET, searchqueryset=None, load_all=True)
if form.is_valid():
query = form.cleaned_data["q"]
results = form.search()
if results.query.backend.include_spelling:
suggestion = form.get_suggestion()
search_list = [r.object for r in results]
paginator = Paginator(search_list, settings.RESULTS_PER_PAGE)
page = request.GET.get("page")
try:
results = paginator.page(page)
except PageNotAnInteger:
# if page is not an integer, deliver first page.
results = paginator.page(1)
except EmptyPage:
# if page is out of range (e.g. 999), deliver last page of results
results = paginator.page(paginator.num_pages)
if results.has_next():
next_page_num = results.next_page_number()
else:
next_page_num = 0 # way of indicating no more pages... 1 index'd helped!
if results.has_previous():
prev_page_num = results.previous_page_number()
else:
prev_page_num = 0
results = results.object_list
return render_to_response(
"search/search.html",
{
"query": query,
"suggestion": suggestion,
"results": results,
"next_page": next_page_num,
"prev_page": prev_page_num,
},
context_instance=RequestContext(request),
)