如何通过Django查询Postgres索引

时间:2017-04-17 00:38:45

标签: python django postgresql django-models

我想在我的网络应用中添加文字搜索功能。我在postgres中为三个字段创建了一个索引。我无法弄清楚你如何从django视图中查询索引。

索引命名为' search_index'当我尝试查询search_index时,我收到一个字段错误。

的观点

def search(request):
    # search_index
    #products = Product.objects.defer('product_description', 'product_keywords', 'shipping_cost', 'promotional_text', 'condition', 'warranty', 'stock', 'sku')
    #product_count = products.count()
    query = request.GET.get("q")
    if query:
        # product = products.filter(
        #     Q(product_name__icontains=query) |
        #     Q(product_description__icontains=query) |
        #     Q(product_keywords__icontains=query)
        # )
        product = Product.objects.filter(search_index__search=query)
        # if product.order_by('sale_price'):
        #     product = product.order_by('sale_price')
        # else:
        #     product = product.order_by('-price')

        paginator = Paginator(product, 20)
        page = request.GET.get('page')

        try:
            product = paginator.page(page)
        except PageNotAnInteger:
            product = paginator.page(1)
        except EmptyPage:
            product = paginator.page(paginator.num_pages)

        index = product.number - 1
        max_index = len(paginator.page_range)
        start_index = index - 5 if index >= 5 else 0
        end_index = index + 5 if index <= max_index - 5 else max_index
        page_range = paginator.page_range[start_index:end_index]

        context = {"product": product, "page_range": page_range, "query": query,}
        template = "search.html"

    else:
        template = "search.html"
        context = {
                   "query": query,
                   #"product_count": product_count,
                   }

    return render(request, template, context)

回溯

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/search/?q=born

Django Version: 1.10.6
Python Version: 3.6.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'whitenoise.runserver_nostatic',
 'django.contrib.sitemaps',
 'django.contrib.sites',
 'django.contrib.flatpages',
 'crispy_forms',
 'products',
 'blog',
 'newsletter',
 'debug_toolbar']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.gzip.GZipMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
 'debug_toolbar.middleware.DebugToolbarMiddleware']



Traceback:

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  42.             response = get_response(request)

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
  149.                     response = view_func(request, *args, **kwargs)

File "/Users/Tommy/Desktop/django/compare/compare/compare/views.py" in search
  31.         product = Product.objects.filter(search_index__search=query)

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/db/models/manager.py" in manager_method
  85.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/db/models/query.py" in filter
  796.         return self._filter_or_exclude(False, *args, **kwargs)

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/db/models/query.py" in _filter_or_exclude
  814.             clone.query.add_q(Q(*args, **kwargs))

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/db/models/sql/query.py" in add_q
  1227.         clause, _ = self._add_q(q_object, self.used_aliases)

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/db/models/sql/query.py" in _add_q
  1253.                     allow_joins=allow_joins, split_subq=split_subq,

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/db/models/sql/query.py" in build_filter
  1133.         lookups, parts, reffed_expression = self.solve_lookup_type(arg)

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/db/models/sql/query.py" in solve_lookup_type
  1019.         _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())

File "/Users/Tommy/Desktop/django/compare/lib/python3.6/site-packages/django/db/models/sql/query.py" in names_to_path
  1327.                                      "Choices are: %s" % (name, ", ".join(available)))

Exception Type: FieldError at /search/
Exception Value: Cannot resolve keyword 'search_index' into field. Choices are: buy_link, category, category_id, company, company_id, condition, date_added, id, manufacturer, manufacturer_id, orginial_price, price, product_description, product_image_url, product_keywords, product_name, promotional_text, sale_price, shipping_cost, sku, slug, stock, updated, views, warranty

1 个答案:

答案 0 :(得分:0)

我认为这可能就像您忘记在'django.contrib.postgres'的{​​{1}}列表中添加INSTALLED_APPS一样简单。

请在此处查看有关该特定功能的文档:https://docs.djangoproject.com/en/1.11/ref/contrib/postgres/search/#the-search-lookup