[Django]-Logging Django Haystack search keyword

7πŸ‘

βœ…

I wanted to do something similar so I created an app named search

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

search/urls.py

from django.conf.urls.defaults import *

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

then of course in my project urls I added the following rule:

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

search/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 so that only on the first page of search results, a SearchQuery is saved

each SearchQuery is unique in the DB.

each SearchQuery for a SearchTerm is recorded with additional info such as user (nullable) and when the term was searched.

view = SearchView() and return view(request) make it so that aftera a SearchQuery is recorded, the default haystack views get called for that request.

5πŸ‘

Probably the easiest solution is to subclass SearchView and use it instead in your urlpatterns.

Haystack SearchView is unfortunately written in different manner than Django Class Based Views (probably because it was written before CBV were introduced to Django…), but it is very straightforward piece of code https://github.com/toastdriven/django-haystack/blob/master/haystack/views.py#L13

Something like this should work:

class LoggingSearchView(SearchView):

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

2πŸ‘

Haystack related saved_searches app allows storing a user’s search history:

https://github.com/toastdriven/saved_searches

πŸ‘€bmihelac

Leave a comment