我想做类似的事情,所以我创建了一个名为search的应用程序
搜索/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 视图。