2013-02-22 45 views
3

我在url.py如下:記錄Django的草垛搜索關鍵字

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'), 
... 

它工作正常,但我需要捕捉搜索關鍵字來記錄它。

如何捕獲它?

您的幫助,將不勝感激。

+0

你在用什麼搜索引擎?也許它會更聰明地監視引擎本身? http://wiki.apache.org/solr/SolrLogging否則我認爲擴展SearchView將是最好的舉動。 – fsw 2013-03-03 10:41:52

回答

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添加以下規則:

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是在DB獨特。

SearchTerm的每個SearchQuery都會記錄其他信息,例如user(可爲空)和when該術語被搜索。

view = SearchView()return view(request)使得它記錄了SearchQuery後,會爲該請求調用默認的乾草堆視圖。

5

也許最簡單的解決辦法是子類搜索查看,並在你的URL模式用它來代替。

草垛搜索查看不幸用不同的方式比基於Django的類視圖(可能是因爲之前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()