开发者

In django-haystack, how can I use subclasses of models?

I'm trying to get django-haystack (using a xapian backend) to index my model here for search, by the name and description fields.

I have a subclass of Item, Device, which adds a manufacturer field.

The Item model is defined thusly:

class Item(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(null=True, blank=True)
    compatible_with = models.ManyToManyField('self', null=True, blank=True)
    often_with = models.ManyToManyField('self', null=True, blank=True)
    cr开发者_高级运维eated_by = models.ForeignKey(User, null=True, blank=True, related_name='created_by')
    verified = models.BooleanField(default=False)
    verified_by = models.ForeignKey(User, null=True, blank=True, related_name='verified_by')
    date_created = models.DateField(auto_now_add=True)
    slug = models.SlugField(max_length=300, null=True, blank=True)

My subclass of django-haystack’s SearchIndex looks like this:

class ItemIndex(SearchIndex):
    text = CharField(document=True, use_template=True)
    name = CharField(model_attr='name')
    description = CharField(model_attr='description')

site.register(Item, ItemIndex)

I have set up this template, in templates/search/indexes/catalog/item_text.txt:

{{ object.name }}
{{ object.description }}

What do I add to item_text.txt such that the manufacturer field gets indexed, if and only if the model object is an instance of Device?


{% if device.manufacturer %}
{{ device.manufacturer }}
{% endif %}

... the Haystack tutorial is a bit confusing on this subject (you don't actually have to use a text-file template, for one) but the basic idea is that Haystack's engine goes to town on whatever text data is in this template.

... Actually, it goes to town on whatever is in the response you send it, but if you've got the template set up you can use whatever Django template logic you want in there.

(note that the if template tag was a bit of a dog's breakfast prior to Django 1.2; if you're stuck on an earlier Django version you may have to tweak the syntax, but the principle is the same.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜