Skip to content

Instantly share code, notes, and snippets.

@terryh
Created March 16, 2011 15:08
Show Gist options
  • Select an option

  • Save terryh/872626 to your computer and use it in GitHub Desktop.

Select an option

Save terryh/872626 to your computer and use it in GitHub Desktop.
Example models.py file for djang-haystack
# models.py
from django.db import models
from django.contrib.auth.models import User
import datetime
class Ejournal(models.Model):
user = models.ForeignKey(User)
title = models.CharField( max_length=200)
author = models.ManyToManyField(blank=True, null=True)
publisher = models.CharField(default='', blank=True, max_length=200)
publish_date = models.DateTimeField( default=datetime.datetime.now )
abstract = models.TextField(default='', blank=True )
categories = models.ManyToManyField('Category', blank=True, null=True)
def __unicode__(self):
return self.title
class Category(models.Model):
title = models.CharField(max_length=200)
title_zh = models.CharField(max_length=200)
parent = models.ForeignKey('self', blank=True, null=True)
def __unicode__(self):
return self.parent and "%s---%s" % (self.parent.title, self.title) or self.title
class Author(models.Model):
title = models.CharField(max_length=200)
def __unicode__(self):
return self.title
# search_indexes.py
import datetime
from haystack.indexes import *
from haystack import site
from ejournal.models import Ejournal, Category, Author
class EjournalIndex(RealTimeSearchIndex):
text = CharField(document=True, use_template=True)
publish_date = DateTimeField(model_attr='publish_date')
publisher = CharField(model_attr='publisher')
language = CharField(model_attr='language')
categories = MultiValueField(faceted=True)
author = MultiValueField(faceted=True)
def prepare_categories(self, obj):
return [item.title for item in obj.categories.all()]
def prepare_author(self, obj):
return [item.title for item in obj.author.all()]
def get_queryset(self):
"""Used when the entire index for model is updated."""
return Ejournal.objects.filter(publish_date__lte=datetime.datetime.now())
def _setup_save(self, model):
super(EjournalIndex, self)._setup_save(model)
signals.m2m_changed.connect( self.update_object, sender=Ejournal.author.through)
site.register(Ejournal, EjournalIndex)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment