本文整理汇总了Python中questions.models.Question.search方法的典型用法代码示例。如果您正苦于以下问题:Python Question.search方法的具体用法?Python Question.search怎么用?Python Question.search使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类questions.models.Question
的用法示例。
在下文中一共展示了Question.search方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_added
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_added(self):
# Create a question--that adds one document to the index.
q = question(title=u'Does this test work?', save=True)
self.refresh()
eq_(Question.search().query(
or_=dict(('%s__text' % field, 'test')
for field in Question.get_query_fields())).count(),
1)
# Create an answer for the question. It shouldn't be searchable
# until the answer is saved.
a = answer(content=u'There\'s only one way to find out!',
question=q)
self.refresh()
eq_(Question.search().query(
or_=dict(('%s__text' % field, 'only')
for field in Question.get_query_fields())).count(),
0)
a.save()
self.refresh()
eq_(Question.search().query(
or_=dict(('%s__text' % field, 'only')
for field in Question.get_query_fields())).count(),
1)
# Make sure that there's only one question document in the
# index--creating an answer should have updated the existing
# one.
eq_(Question.search().count(), 1)
示例2: test_cron_updates_counts
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_cron_updates_counts(self):
q = question(save=True)
self.refresh()
eq_(q.num_votes_past_week, 0)
# NB: Need to call .values_dict() here and later otherwise we
# get a Question object which has data from the database and
# not the index.
document = (Question.search()
.values_dict('question_num_votes_past_week')
.filter(id=q.id))[0]
eq_(document['question_num_votes_past_week'], 0)
vote = questionvote(question=q, anonymous_id='abc123')
vote.save()
q.num_votes_past_week = 0
q.save()
update_weekly_votes()
self.refresh()
q = Question.objects.get(pk=q.pk)
eq_(1, q.num_votes_past_week)
document = (Question.search()
.values_dict('question_num_votes_past_week')
.filter(id=q.id))[0]
eq_(document['question_num_votes_past_week'], 1)
示例3: test_question_no_answers_deleted
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_question_no_answers_deleted(self):
q = question(title=u'Does this work?', save=True)
self.refresh()
eq_(Question.search().query('work').count(), 1)
q.delete()
self.refresh()
eq_(Question.search().query('work').count(), 0)
示例4: test_question_questionvote
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_question_questionvote(self):
# Create a question and verify it doesn't show up in a
# query for num_votes__gt=0.
q = question(title=u'model makers will inherit the earth', save=True)
self.refresh()
eq_(Question.search().filter(num_votes__gt=0).count(), 0)
# Add a QuestionVote--it should show up now.
questionvote(question=q, save=True)
self.refresh()
eq_(Question.search().filter(num_votes__gt=0).count(), 1)
示例5: test_questions_tags
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_questions_tags(self):
"""Make sure that adding tags to a Question causes it to
refresh the index.
"""
tag = u'hiphop'
eq_(Question.search().filter(tag=tag).count(), 0)
q = question(save=True)
self.refresh()
eq_(Question.search().filter(tag=tag).count(), 0)
q.tags.add(tag)
self.refresh()
eq_(Question.search().filter(tag=tag).count(), 1)
q.tags.remove(tag)
self.refresh()
eq_(Question.search().filter(tag=tag).count(), 0)
示例6: test_case_insensitive_search
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_case_insensitive_search(self):
"""Ensure the default searcher is case insensitive."""
answervote(
answer=answer(question=question(title="lolrus", content="I am the lolrus.", save=True), save=True),
helpful=True,
).save()
self.refresh()
result = Question.search().query("LOLRUS")
assert len(result) > 0
示例7: test_case_insensitive_search
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_case_insensitive_search(self):
"""Ensure the default searcher is case insensitive."""
answervote(
answer=answer(question=question(title='lolrus',
content='I am the lolrus.',
save=True),
save=True),
helpful=True).save()
self.refresh()
result = Question.search().query('LOLRUS')
assert result.count() > 0
示例8: test_added
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_added(self):
# Create a question--that adds one document to the index.
q = question(title=u"Does this test work?", save=True)
self.refresh()
eq_(Question.search().query("test").count(), 1)
# Create an answer for the question. It shouldn't be searchable
# until the answer is saved.
a = answer(content=u"There's only one way to find out!", question=q)
self.refresh()
eq_(Question.search().query("only").count(), 0)
a.save()
self.refresh()
eq_(Question.search().query("only").count(), 1)
# Make sure that there's only one question document in the
# index--creating an answer should have updated the existing
# one.
eq_(Question.search().count(), 1)
示例9: test_question_one_answer_deleted
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_question_one_answer_deleted(self):
q = question(title=u'are model makers the new pink?', save=True)
a = answer(content=u'yes.', question=q, save=True)
self.refresh()
# Question and its answers are a single document--so the
# index count should be only 1.
eq_(Question.search().query('pink').count(), 1)
# After deleting the answer, the question document should
# remain.
a.delete()
self.refresh()
eq_(Question.search().query('pink').count(), 1)
# Delete the question and it should be removed from the
# index.
q.delete()
self.refresh()
eq_(Question.search().query('pink').count(), 0)
示例10: test_question_topics
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_question_topics(self):
"""Make sure that adding topics to a Question causes it to
refresh the index.
"""
t = topic(slug=u'hiphop', save=True)
eq_(Question.search().filter(topic=t.slug).count(), 0)
q = question(save=True)
self.refresh()
eq_(Question.search().filter(topic=t.slug).count(), 0)
q.topics.add(t)
self.refresh()
eq_(Question.search().filter(topic=t.slug).count(), 1)
q.topics.clear()
self.refresh()
# Make sure the question itself is still there and that we didn't
# accidentally delete it through screwed up signal handling:
eq_(Question.search().filter().count(), 1)
eq_(Question.search().filter(topic=t.slug).count(), 0)
示例11: test_question_products
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def test_question_products(self):
"""Make sure that adding products to a Question causes it to
refresh the index.
"""
p = product(slug=u'desktop', save=True)
eq_(Question.search().filter(product=p.slug).count(), 0)
q = question(save=True)
self.refresh()
eq_(Question.search().filter(product=p.slug).count(), 0)
q.products.add(p)
self.refresh()
eq_(Question.search().filter(product=p.slug).count(), 1)
q.products.remove(p)
self.refresh()
# Make sure the question itself is still there and that we didn't
# accidentally delete it through screwed up signal handling:
eq_(Question.search().filter().count(), 1)
eq_(Question.search().filter(product=p.slug).count(), 0)
示例12: suggestions
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def suggestions(request):
"""A simple search view that returns OpenSearch suggestions."""
mimetype = 'application/x-suggestions+json'
term = request.GET.get('q')
if not term:
return HttpResponseBadRequest(mimetype=mimetype)
site = Site.objects.get_current()
locale = locale_or_default(request.locale)
try:
query = dict(('%s__text' % field, term)
for field in Document.get_query_fields())
wiki_s = (Document.search()
.filter(document_is_archived=False)
.filter(document_locale=locale)
.values_dict('document_title', 'url')
.query(or_=query)[:5])
query = dict(('%s__text' % field, term)
for field in Question.get_query_fields())
question_s = (Question.search()
.filter(question_has_helpful=True)
.values_dict('question_title', 'url')
.query(or_=query)[:5])
results = list(chain(question_s, wiki_s))
except (ESTimeoutError, ESMaxRetryError, ESException):
# If we have ES problems, we just send back an empty result
# set.
results = []
urlize = lambda r: u'https://%s%s' % (site, r['url'])
titleize = lambda r: (r['document_title'] if 'document_title' in r
else r['question_title'])
data = [term,
[titleize(r) for r in results],
[],
[urlize(r) for r in results]]
return HttpResponse(json.dumps(data), mimetype=mimetype)
示例13: _search_suggestions
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def _search_suggestions(request, text, locale, product_slugs):
"""Return an iterable of the most relevant wiki pages and questions.
:arg text: full text to search on
:arg locale: locale to limit to
:arg product_slugs: list of product slugs to filter articles on
(["desktop", "mobile", ...])
Items are dicts of::
{
'type':
'search_summary':
'title':
'url':
'object':
}
:returns: up to 3 wiki pages, then up to 3 questions.
"""
# TODO: this can be reworked to pull data from ES rather than
# hit the db.
question_s = Question.search()
wiki_s = Document.search()
# Max number of search results per type.
WIKI_RESULTS = QUESTIONS_RESULTS = 3
default_categories = settings.SEARCH_DEFAULT_CATEGORIES
# Apply product filters
if product_slugs:
wiki_s = wiki_s.filter(product__in=product_slugs)
question_s = question_s.filter(product__in=product_slugs)
results = []
try:
# Search for relevant KB documents.
query = dict(('%s__text' % field, text)
for field in Document.get_query_fields())
query.update(dict(('%s__text_phrase' % field, text)
for field in Document.get_query_fields()))
filter = F()
filter |= F(document_locale=locale)
filter |= F(document_locale=settings.WIKI_DEFAULT_LANGUAGE)
filter &= F(document_category__in=default_categories)
filter &= F(document_is_archived=False)
raw_results = (
wiki_s.filter(filter)
.query(or_=query)
.values_dict('id')[:WIKI_RESULTS])
for r in raw_results:
try:
doc = (Document.objects.select_related('current_revision')
.get(pk=r['id']))
results.append({
'search_summary': clean_excerpt(
doc.current_revision.summary),
'url': doc.get_absolute_url(),
'title': doc.title,
'type': 'document',
'object': doc,
})
except Document.DoesNotExist:
pass
# Search for relevant questions.
query = dict(('%s__text' % field, text)
for field in Question.get_query_fields())
query.update(dict(('%s__text_phrase' % field, text)
for field in Question.get_query_fields()))
max_age = int(time.time()) - settings.SEARCH_DEFAULT_MAX_QUESTION_AGE
# Filter questions by language. Questions should be either in English
# or in the locale's language. This is because we have some questions
# marked English that are really in other languages. The assumption
# being that if a native speakers submits a query in given language,
# the items that are written in that language will automatically match
# better, so questions incorrectly marked as english can be found too.
question_filter = F(question_locale=locale)
question_filter |= F(question_locale=settings.WIKI_DEFAULT_LANGUAGE)
question_filter &= F(updated__gte=max_age)
raw_results = (question_s
.query(or_=query)
.filter(question_filter)
.values_dict('id')[:QUESTIONS_RESULTS])
for r in raw_results:
try:
q = Question.objects.get(pk=r['id'])
results.append({
'search_summary': clean_excerpt(q.content[0:500]),
'url': q.get_absolute_url(),
'title': q.title,
'type': 'question',
'object': q,
'is_solved': q.is_solved,
'num_answers': q.num_answers,
#.........这里部分代码省略.........
示例14: search
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def search(request, template=None):
"""ES-specific search view"""
if (waffle.flag_is_active(request, 'esunified') or
request.GET.get('esunified')):
return search_with_es_unified(request, template)
start = time.time()
# JSON-specific variables
is_json = (request.GET.get('format') == 'json')
callback = request.GET.get('callback', '').strip()
mimetype = 'application/x-javascript' if callback else 'application/json'
# Search "Expires" header format
expires_fmt = '%A, %d %B %Y %H:%M:%S GMT'
# Check callback is valid
if is_json and callback and not jsonp_is_valid(callback):
return HttpResponse(
json.dumps({'error': _('Invalid callback function.')}),
mimetype=mimetype, status=400)
language = locale_or_default(request.GET.get('language', request.locale))
r = request.GET.copy()
a = request.GET.get('a', '0')
# Search default values
try:
category = (map(int, r.getlist('category')) or
settings.SEARCH_DEFAULT_CATEGORIES)
except ValueError:
category = settings.SEARCH_DEFAULT_CATEGORIES
r.setlist('category', category)
# Basic form
if a == '0':
r['w'] = r.get('w', constants.WHERE_BASIC)
# Advanced form
if a == '2':
r['language'] = language
r['a'] = '1'
# TODO: Rewrite so SearchForm is unbound initially and we can use
# `initial` on the form fields.
if 'include_archived' not in r:
r['include_archived'] = False
search_form = SearchForm(r)
if not search_form.is_valid() or a == '2':
if is_json:
return HttpResponse(
json.dumps({'error': _('Invalid search data.')}),
mimetype=mimetype,
status=400)
t = template if request.MOBILE else 'search/form.html'
search_ = jingo.render(request, t,
{'advanced': a, 'request': request,
'search_form': search_form})
search_['Cache-Control'] = 'max-age=%s' % \
(settings.SEARCH_CACHE_PERIOD * 60)
search_['Expires'] = (datetime.utcnow() +
timedelta(
minutes=settings.SEARCH_CACHE_PERIOD)) \
.strftime(expires_fmt)
return search_
cleaned = search_form.cleaned_data
page = max(smart_int(request.GET.get('page')), 1)
offset = (page - 1) * settings.SEARCH_RESULTS_PER_PAGE
lang = language.lower()
if settings.LANGUAGES.get(lang):
lang_name = settings.LANGUAGES[lang]
else:
lang_name = ''
wiki_s = Document.search()
question_s = Question.search()
discussion_s = Thread.search()
# wiki filters
# Category filter
if cleaned['category']:
wiki_s = wiki_s.filter(document_category__in=cleaned['category'])
# Locale filter
wiki_s = wiki_s.filter(document_locale=language)
# Product filter
products = cleaned['product']
for p in products:
wiki_s = wiki_s.filter(document_tag=p)
# Tags filter
tags = [t.strip() for t in cleaned['tags'].split()]
for t in tags:
#.........这里部分代码省略.........
示例15: search_with_es
# 需要导入模块: from questions.models import Question [as 别名]
# 或者: from questions.models.Question import search [as 别名]
def search_with_es(request, template=None):
"""ES-specific search view"""
engine = "elastic"
# Time ES and Sphinx separate. See bug 723930.
# TODO: Remove this once Sphinx is gone.
start = time.time()
# JSON-specific variables
is_json = request.GET.get("format") == "json"
callback = request.GET.get("callback", "").strip()
mimetype = "application/x-javascript" if callback else "application/json"
# Search "Expires" header format
expires_fmt = "%A, %d %B %Y %H:%M:%S GMT"
# Check callback is valid
if is_json and callback and not jsonp_is_valid(callback):
return HttpResponse(json.dumps({"error": _("Invalid callback function.")}), mimetype=mimetype, status=400)
language = locale_or_default(request.GET.get("language", request.locale))
r = request.GET.copy()
a = request.GET.get("a", "0")
# Search default values
try:
category = map(int, r.getlist("category")) or settings.SEARCH_DEFAULT_CATEGORIES
except ValueError:
category = settings.SEARCH_DEFAULT_CATEGORIES
r.setlist("category", category)
# Basic form
if a == "0":
r["w"] = r.get("w", constants.WHERE_BASIC)
# Advanced form
if a == "2":
r["language"] = language
r["a"] = "1"
# TODO: Rewrite so SearchForm is unbound initially and we can use
# `initial` on the form fields.
if "include_archived" not in r:
r["include_archived"] = False
search_form = SearchForm(r)
if not search_form.is_valid() or a == "2":
if is_json:
return HttpResponse(json.dumps({"error": _("Invalid search data.")}), mimetype=mimetype, status=400)
t = template if request.MOBILE else "search/form.html"
search_ = jingo.render(request, t, {"advanced": a, "request": request, "search_form": search_form})
search_["Cache-Control"] = "max-age=%s" % (settings.SEARCH_CACHE_PERIOD * 60)
search_["Expires"] = (datetime.utcnow() + timedelta(minutes=settings.SEARCH_CACHE_PERIOD)).strftime(expires_fmt)
return search_
cleaned = search_form.cleaned_data
page = max(smart_int(request.GET.get("page")), 1)
offset = (page - 1) * settings.SEARCH_RESULTS_PER_PAGE
# TODO: This is fishy--why does it have to be coded this way?
# get language name for display in template
lang = language.lower()
if settings.LANGUAGES.get(lang):
lang_name = settings.LANGUAGES[lang]
else:
lang_name = ""
wiki_s = Document.search()
question_s = Question.search()
discussion_s = Thread.search()
# wiki filters
# Category filter
if cleaned["category"]:
wiki_s = wiki_s.filter(document_category__in=cleaned["category"])
# Locale filter
wiki_s = wiki_s.filter(document_locale=language)
# Product filter
products = cleaned["product"]
for p in products:
wiki_s = wiki_s.filter(document_tag=p)
# Tags filter
tags = [t.strip() for t in cleaned["tags"].split()]
for t in tags:
wiki_s = wiki_s.filter(document_tag=t)
# Archived bit
if a == "0" and not cleaned["include_archived"]:
# Default to NO for basic search:
cleaned["include_archived"] = False
if not cleaned["include_archived"]:
wiki_s = wiki_s.filter(document_is_archived=False)
# End of wiki filters
#.........这里部分代码省略.........