记录Django Haystack搜索关键字

时间:2013-02-22 21:30:27

标签: python django django-haystack

我的url.py中有以下内容:

from haystack.forms import HighlightedModelSearchForm
from haystack.query import SearchQuerySet
from haystack.views import SearchView
from articles.models import Article

article_sqs = SearchQuerySet().models(Article)

urlpatterns = patterns('',
    ...
    url(r'^article/search/$', SearchView(
        template='articles/search/results.html',
        searchqueryset=article_sqs,
        results_per_page=10,
        form_class=HighlightedModelSearchForm
    ), name='haystack_search'),
...

它工作正常,但我需要捕获搜索关键字来记录它。

我该如何捕捉它?

我们将不胜感激。

3 个答案:

答案 0 :(得分:7)

我想做类似的事情,所以我创建了一个名为搜索

的应用

搜索/ models.py

from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _

class SearchTerm(models.Model):
    query = models.CharField(
        verbose_name = _(u'Search Term'),
        max_length = 255,
        default = None
    )

class SearchQuery(models.Model):
    term = models.ForeignKey(
        SearchTerm
    )
    user = models.ForeignKey(
        User,
        blank = True, 
        null = True,
    )
    when = models.DateTimeField(
        verbose_name = _(u'Date Searched'),
    )

搜索/ urls.py

from django.conf.urls.defaults import *

urlpatterns = patterns('',
    url(r'^search/', 'search.views.search', name="search"),
)

然后当然在我的项目网址中我添加了以下规则:

url(r'^', include('search.urls')),

搜索/ views.py

from django.http import HttpResponse
from django.shortcuts import get_object_or_404, render, redirect
from haystack.forms import ModelSearchForm, SearchForm
from haystack.views import SearchView
from search.models import SearchQuery, SearchTerm
import datetime

def search(request):
    if 'page' not in request.GET :
        try :
            st, created = SearchTerm.objects.get_or_create(query=request.GET['q'])
            sq = SearchQuery()
            sq.term = st
            sq.user = request.user
            sq.when = datetime.datetime.now()
            sq.save()
        except :
            pass

    view = SearchView()
    return view(request)

if 'page' not in request.GET以便只在搜索结果的第一页上保存SearchQuery

每个SearchQuery在数据库中都是唯一的。

SearchTerm的每个SearchQuery都会记录其他信息,例如user(可为空)和when搜索的字词。

view = SearchView()return view(request)使得在记录SearchQuery之后,会为该请求调用默认的haystack视图。

答案 1 :(得分:5)

最简单的解决方案可能是将SearchView子类化并在您的urlpatterns中使用它。

不幸的是,Haystack SearchView以不同于Django Class Based Views的方式编写(可能是因为它是在将CBV引入Django之前编写的......),但它是非常简单的代码段https://github.com/toastdriven/django-haystack/blob/master/haystack/views.py#L13

这样的事情应该有效:

class LoggingSearchView(SearchView):

    def create_response(self):
        logger.info(self.query)  #or log self.query as you like
        return super(LoggingSearchView, self).create_response()

答案 2 :(得分:2)

与Haystack相关的saved_searches应用程序允许存储用户的搜索历史记录:

https://github.com/toastdriven/saved_searches