本文整理汇总了Python中haystack.query.SearchQuerySet方法的典型用法代码示例。如果您正苦于以下问题:Python query.SearchQuerySet方法的具体用法?Python query.SearchQuerySet怎么用?Python query.SearchQuerySet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类haystack.query
的用法示例。
在下文中一共展示了query.SearchQuerySet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: handle_delete
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def handle_delete(self, sender, instance, **kwargs):
# modified from BaseSignalProcessor.handle_delete to force checking existence before removing from the index
# (and getting an error message if it's not there).
using_backends = self.connection_router.for_write(instance=instance)
for using in using_backends:
try:
index = self.connections[using].get_unified_index().get_index(sender)
# check to see if the object is actually in the index before removing:
index.prepare(instance)
ct = index.prepared_data['django_ct']
obj_id = index.prepared_data['id']
existing = SearchQuerySet().models(sender).filter(django_ct=ct, id=obj_id)
if existing.count() > 0:
index.remove_object(instance, using=using)
except NotHandled:
pass
示例2: test_from_queryset
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def test_from_queryset(self):
""" Verify that a DistinctCountsSearchQuerySet can be built from an existing SearchQuerySet."""
course_1 = CourseFactory()
CourseRunFactory(title='foo', course=course_1)
CourseRunFactory(title='foo', course=course_1)
course_2 = CourseFactory()
CourseRunFactory(title='foo', course=course_2)
CourseRunFactory(title='bar', course=course_2)
queryset = SearchQuerySet().filter(title='foo').models(CourseRun)
dc_queryset = DistinctCountsSearchQuerySet.from_queryset(queryset)
expected = sorted([run.key for run in queryset])
actual = sorted([run.key for run in dc_queryset])
assert expected == actual
示例3: test_with_distinct_counts_raises_when_queryset_includes_unsupported_options
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def test_with_distinct_counts_raises_when_queryset_includes_unsupported_options(self):
"""
Verify that an error is raised if the original queryset includes options that are not supported by our
custom Query class.
"""
dc_queryset = DistinctCountsSearchQuerySet.from_queryset(SearchQuerySet())
with pytest.raises(RuntimeError) as err:
now = datetime.datetime.now()
ten_days = datetime.timedelta(days=10)
start = now - ten_days
end = now + ten_days
dc_queryset.date_facet('start', start, end, 'day').with_distinct_counts('aggregation_key')
assert str(err.value) == 'DistinctCountsSearchQuery does not support date facets.'
with pytest.raises(RuntimeError) as err:
dc_queryset.facet('pacing_type', order='term').with_distinct_counts('aggregation_key')
assert 'DistinctCountsSearchQuery only supports a limited set of field facet options.' in str(err.value)
示例4: test_enrollable_paid_seat_boosting
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def test_enrollable_paid_seat_boosting(self, has_enrollable_paid_seats, paid_seat_enrollment_end, expects_boost):
"""
Verify that CourseRuns for which an unenrolled user may enroll and
purchase a paid Seat are boosted.
"""
# Create a control record (one that should never be boosted).
with patch.object(CourseRun, 'has_enrollable_paid_seats', return_value=False):
with patch.object(CourseRun, 'get_paid_seat_enrollment_end', return_value=None):
self.build_normalized_course_run(title='test1')
# Create the test record (may be boosted).
with patch.object(CourseRun, 'has_enrollable_paid_seats', return_value=has_enrollable_paid_seats):
with patch.object(CourseRun, 'get_paid_seat_enrollment_end', return_value=paid_seat_enrollment_end):
test_record = self.build_normalized_course_run(title='test2')
search_results = SearchQuerySet().models(CourseRun).all()
assert len(search_results) == 2
if expects_boost:
assert search_results[0].score > search_results[1].score
assert test_record.title == search_results[0].title
else:
assert search_results[0].score == search_results[1].score
示例5: test_enrollable_course_run_boosting
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def test_enrollable_course_run_boosting(self, enrollment_start, enrollment_end, expects_boost):
"""Verify that enrollable CourseRuns are boosted."""
# Create a control record that should never be boosted
self.build_normalized_course_run(title='test1')
# Create the test record
test_record = self.build_normalized_course_run(
title='test2',
enrollment_start=enrollment_start,
enrollment_end=enrollment_end
)
search_results = SearchQuerySet().models(CourseRun).all()
assert len(search_results) == 2
if expects_boost:
assert search_results[0].score > search_results[1].score
assert test_record.title == search_results[0].title
else:
assert search_results[0].score == search_results[1].score
示例6: search
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def search(cls, query, queryset=None):
""" Queries the search index.
Args:
query (str) -- Elasticsearch querystring (e.g. `title:intro*`)
queryset (models.QuerySet) -- base queryset to search, defaults to objects.all()
Returns:
QuerySet
"""
query = clean_query(query)
if queryset is None:
queryset = cls.objects.all()
if query == '(*)':
# Early-exit optimization. Wildcard searching is very expensive in elasticsearch. And since we just
# want everything, we don't need to actually query elasticsearch at all.
return queryset
results = SearchQuerySet().models(cls).raw_search(query)
ids = {result.pk for result in results}
return queryset.filter(pk__in=ids)
示例7: solr_counts
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def solr_counts():
total_q = SearchQuerySet()
latest_q = total_q.filter(latest=True)
registrations_q = latest_q.filter(category="entity_status::ACT")
last_24h = datetime.now() - timedelta(days=1)
last_week = datetime.now() - timedelta(days=7)
last_month = datetime.now() - timedelta(days=30)
last_24h_q = total_q.filter(create_timestamp__gte=last_24h)
last_week_q = total_q.filter(create_timestamp__gte=last_week)
last_month_q = total_q.filter(create_timestamp__gte=last_month)
try:
return {
"total_indexed_items": total_q.count(),
"active": latest_q.count(),
"registrations": registrations_q.count(),
"last_month": last_month_q.count(),
"last_week": last_week_q.count(),
"last_24h": last_24h_q.count(),
}
except SolrError:
LOGGER.exception("Error when retrieving quickload counts from Solr")
return False
示例8: list
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def list(self, request):
search_string = request.query_params.get('q')
if search_string:
try:
book = models.Book.objects.get_for_user(self.request.user)
except models.Book.DoesNotExist:
# rethink the logic here - how could a user not have a book?
return Response(
"No contacts for user",
status=status.HTTP_400_BAD_REQUEST,
)
results = SearchQuerySet().filter(book=book.id).filter(
SQ(name=AutoQuery(search_string)) | SQ(content=AutoQuery(search_string))
)
results = [result.object for result in results]
else:
results = models.Contact.objects.get_contacts_for_user(
self.request.user,
)
serializer = serializers.ContactSerializer(results, many=True)
return Response(serializer.data)
示例9: solr_counts
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def solr_counts():
total_q = SearchQuerySet()
latest_q = total_q.filter(latest=True)
registrations_q = latest_q.filter(category="entity_status::ACT")
last_24h = datetime.now() - timedelta(days=1)
last_week = datetime.now() - timedelta(days=7)
last_month = datetime.now() - timedelta(days=30)
last_24h_q = total_q.filter(create_timestamp__gte=last_24h)
last_week_q = total_q.filter(create_timestamp__gte=last_week)
last_month_q = total_q.filter(create_timestamp__gte=last_month)
try:
return {
"total": total_q.count(),
"active": latest_q.count(),
"registrations": registrations_q.count(),
"last_month": last_month_q.count(),
"last_week": last_week_q.count(),
"last_24h": last_24h_q.count(),
}
except SolrError:
LOGGER.exception("Error when retrieving quickload counts from Solr")
return False
示例10: handle
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def handle(self, *args, **options):
sqs = SearchQuerySet()
users = sqs.models(User).all().count()
images = sqs.models(Image).all().count()
integration = 0
for i in sqs.models(Image).all():
integration += i.integration
integration = int(integration / 3600.0)
gs = GlobalStat(
users = users,
images = images,
integration = integration)
gs.save()
示例11: update_top100_ids
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def update_top100_ids():
from astrobin.models import Image
LOCK_EXPIRE = 60 * 5 # Lock expires in 5 minutes
lock_id = 'top100_ids_lock'
# cache.add fails if the key already exists
acquire_lock = lambda: cache.add(lock_id, 'true', LOCK_EXPIRE)
# memcache delete is very slow, but we have to use it to take
# advantage of using add() for atomic locking
release_lock = lambda: cache.delete(lock_id)
logger.debug('Building Top100 ids...')
if acquire_lock():
try:
sqs = SearchQuerySet().models(Image).order_by('-likes')
top100_ids = [int(x.pk) for x in sqs][:100]
cache.set('top100_ids', top100_ids, 60 * 60 * 24)
finally:
release_lock()
return
logger.debug(
'Top100 ids task is already being run by another worker')
示例12: global_stats
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def global_stats():
from astrobin.models import Image, GlobalStat
sqs = SearchQuerySet()
users = sqs.models(User).all().count()
images = sqs.models(Image).all().count()
integration = 0
for i in sqs.models(Image).all():
integration += i.integration
integration = int(integration / 3600.0)
gs = GlobalStat(
users=users,
images=images,
integration=integration)
gs.save()
示例13: handle_item
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def handle_item(self, item):
"""Perform MLT-query on item"""
sqs = SearchQuerySet().models(self.model)
mlt_results = sqs.more_like_this(item)
saved = []
for result in mlt_results: # type: SearchResult
rel = self.model_relation(score=result.score)
rel.set_relation(seed_id=item.pk, related_id=result.pk)
rel.save()
logger.debug('Saved %s' % rel)
saved.append(rel)
return saved
示例14: search
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def search(self):
# First, store the SearchQuerySet received from other processing.
sqs = super().search()
if not self.is_valid():
return self.no_query_found()
# Custom date range filter
# TODO can this be done with native-haystack?
if 'start_date' in self.data:
try:
sqs = sqs.filter(date__gte=datetime.datetime.strptime(self.data.get('start_date'), '%Y-%m-%d'))
except ValueError:
logger.error('Invalid start_date')
if 'end_date' in self.data:
try:
sqs = sqs.filter(date__lte=datetime.datetime.strptime(self.data.get('end_date'), '%Y-%m-%d'))
except ValueError as e:
logger.error('Invalid end_date')
return sqs
示例15: autocomplete_view
# 需要导入模块: from haystack import query [as 别名]
# 或者: from haystack.query import SearchQuerySet [as 别名]
def autocomplete_view(request):
"""Stub for auto-complete feature(title for all objects missing)
"""
suggestions_limit = 5
sqs = SearchQuerySet().autocomplete(title=request.GET.get('q', ''))[:suggestions_limit]
# for result in sqs: # type: SearchResult
# print(result.object)
# print(result.title)
suggestions = [result.title for result in sqs]
return JsonResponse({
'results': suggestions
})