Django + Haystack + Whoosh,没有被索引的模型,搜索结果没有返回

时间:2017-04-27 05:24:52

标签: python django whoosh

我在django 1.10中使用whoosh后端进行了大海捞针搜索实现。我已经关注了#34;入门"文档页面,并实现了我在那里看到的一切,但是,当我运行

./manage.py update_index

它会告诉我

Indexing 0 posts

当我进行测试搜索时,我将无法获得任何结果。我正在创建一个论坛网络应用程序,所有帖子都填充了Lorem Ipsum ...内容。当我搜索" Lorem"它不会向我显示任何结果。

settings.py:

"""
Django settings for portfolio project.

Generated by 'django-admin startproject' using Django 1.11.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '...'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'markdown_deux',
    'haystack',
    'forum',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'portfolio.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, "portfolio/templates"),
            os.path.join(BASE_DIR, "forum/templates"),
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'portfolio.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Haystack configration
# HAYSTACK_CONNECTIONS = {
    # 'default': {
        # 'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        # 'URL': 'http://127.0.0.1:8983/solr'
        # # ...or for multicore...
        # # 'URL': 'http://127.0.0.1:8983/solr/mysite',
    # },
# }
import os
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
        'PATH': os.path.join(os.path.dirname(__file__), 'whoosh_index'),
    },
}


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

LOGIN_REDIRECT_URL = "forum_homepage"
LOGOUT_REDIRECT_URL = "forum_homepage"

search_indexes.py:

"""
Python module for defining models to have haystack index for searching.
"""

from haystack import indexes
from forum.models import Post, Thread


class PostIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True)
    author = indexes.CharField(model_attr="author")
    creation_d = indexes.CharField(model_attr="creation_d")

    def get_model(self):
        "Return a reference to the model being represented."
        return Post

views.py:

...
class SearchView(SearchView):
    """
    Render the view for searching.
    """

    def get_context_data(self, **kwargs):
        "Get context for SearchFormView view."
        context = super(SearchView, self).get_context_data(**kwargs)
        context["active"] = "search"
        return context
...

模板/搜索/ search.html:

{% extends "forum/base_template.html" %}

{% block forum_body %}
    <h2>Search</h2>

    <form method="get" action=".">
        <table>
            {{ form.as_table }}
            <tr>
                <td>&nbsp;</td>
                <td>
                    <input type="submit" value="Search">
                </td>
            </tr>
        </table>

        {% if query %}
            <h3>Results</h3>

            {% for result in page.object_list %}
                <p>
                    <a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a>
                </p>
            {% empty %}
                <p>No results found.</p>
            {% endfor %}

            {% if page.has_previous or page.has_next %}
                <div>
                    {% if page.has_previous %}<a href="?q={{ query }}&amp;page={{ page.previous_page_number }}">{% endif %}&laquo; Previous{% if page.has_previous %}</a>{% endif %}
                    |
                    {% if page.has_next %}<a href="?q={{ query }}&amp;page={{ page.next_page_number }}">{% endif %}Next &raquo;{% if page.has_next %}</a>{% endif %}
                </div>
            {% endif %}
        {% else %}
            {# Show some example queries to run, maybe query syntax, something else? #}
        {% endif %}
    </form>
{% endblock %}

models.py:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.conf import settings

# for referending auth.User model objects
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')

# Create your models here.


class Rules(models.Model):
    """
    Model the set of rules for the forum.

    There is to only be one instance of this model.
    """
    rules = models.TextField()
    name = models.CharField(max_length=5, default="Rules")

    def __str__(self):
        return "Rules"

class Category(models.Model):
    """
    Model a forum main category.
    """

    name = models.CharField(max_length=30, unique=True)

    def __str__(self):
        """
        Represent a main category as a string.
        """
        return self.name

class SubCategory(models.Model):
    """
    Model a forum subcategory.
    """

    name = models.CharField(max_length=30, unique=True)

    # to create a one-to-many field from the category to the subcategories
    # the inverse is automatically created by django and can be accessed
    #   via "Category.subcats"
    category = models.ForeignKey(Category, related_name="subcats")

    def num_threads(self):
        """
        Retrieve the number of threads in the subcategory.
        """
        return self.threads.all().count()

    def num_posts(self):
        """
        Retrieve the number of threads in the subcategory.
        """
        post_count = 0
        for thread in self.threads.all():
            post_count += thread.post_count()
        return post_count

    def __str__(self):
        """
        Represent a subcategory as a string.
        """
        return self.name

class Thread(models.Model):
    """
    Model a single thread in a subcategory.
    """

    name = models.CharField(max_length=30)
    creation_d = models.DateTimeField(auto_now_add=True)
    views = models.IntegerField(default=0)

    # to create a on-to-many field from the threads to the subcategory
    #   in which they belong
    # threads can be accessed via subcats from the "SubCat.threads" field.
    subcat = models.ForeignKey(SubCategory, related_name="threads")

    def __unicode__(self):
        return unicode(self.name)

    def get_author(self):
        """
        Retrieve the author of the thread based on the author of the first post.
        """
        return self.posts.all().order_by("-creation_d")[0].author

    def post_count(self):
        """
        Count number of posts in a thread
        """
        return self.posts.all().count()

    def reply_count(self):
        """
        Count number of replies in a thread
        """
        return self.posts.all().count() - 1

    def get_last_post(self):
        """
        Find information for the last post on a certain thread.
        """
        try:
            return self.posts.all().order_by("-creation_d")[0]
        except KeyError:
            return None

    def __str__(self):
        """
        Represent a thread as a string.
        """
        # return '"{}" by "{}"'.format(self.name, self.author)
        return '"{}"'.format(self.name)

class Post(models.Model):
    """
    Model a single post in a thread.
    """

    creation_d = models.DateTimeField(auto_now_add=True)
    content = models.TextField()

    # to create a one-to-one relationship between a post and an author
    author = models.ForeignKey(AUTH_USER_MODEL, related_name="posts")
    # to create a one-to-many relationship between posts and a thread
    thread = models.ForeignKey(Thread, related_name="posts")

    def __str__(self):
        """
        Represent a post with a string.
        """
        post = (self.content[:17] + '...') if len(self.content) > 20 else self.content
        return '"{}" by {} at {}/{}/{}'.format(post, self.author.username, self.creation_d.month, self.creation_d.day, self.creation_d.year)

任何帮助都会受到赞赏,但我无法弄清楚我做错了什么。

0 个答案:

没有答案