简体   繁体   English

Django-干草堆-如何在搜索索引中表示关系?

[英]Django-haystack - how to represent relations in search indexes?

So I'm trying to index some items with Django-Haystack (elasticsearch backend), one of the indexing criteria being tags on the item, which are a m2m relation(I implemented my own custom solution as it was easier for me than using taggit), here is what my models look like. 因此,我尝试使用Django-Haystack(elasticsearch后端)为某些项目建立索引,索引标准之一是项目上的标签,这是m2m关系(我实现了自己的自定义解决方案,因为比起使用taggit,我更容易实现),这是我的模型的样子。

class GalleryTag(models.Model):
    tag = models.CharField(max_length=100, unique=True)
    slug = AutoSlugField(populate_from='tag', unique=True)

    class Meta:
        abstract = True
    def __unicode__(self):
        return self.tag


class Tag(GalleryTag):
    pass


class Artist(GalleryTag):
    pass


class Character(GalleryTag):
    pass

class Gallery(models.Model):    
    characters = models.ManyToManyField(Character, blank=True, related_name='characters')
    artists = models.ManyToManyField(Artist, blank=True, related_name='artists')
    tags = models.ManyToManyField(Tag, blank=True, related_name='tags')
    def __unicode__(self):
        return self.name

The object I'm trying to index to be searchable is Gallery, and I would like to be able to have the tags, artists, and characters(all the m2ms) be one of the searchable criteria on them. 我想索引为可搜索的对象是Gallery,并且我希望能够将标签,艺术家和字符(所有m2ms)作为它们上可搜索的条件之一。 I could not really find anything about how to make relations searchable, the basic examples only use completely flat models. 我真的找不到有关如何使关系可搜索的任何信息,基本示例仅使用完全平面的模型。 Thanks. 谢谢。

One way to do this would be to pull in the data in the template file of GalleryIndex . 一种方法是将数据GalleryIndex的模板文件中。 Something like: 就像是:

{% for s in object.hasTags.all %}
{{t.tag}}
{% endfor %}

If, for whatever reason, resolving your relation is too complex for a template then add a field called tags to GalleryIndex and add a routine prepare_tags(self, obj) that queries the relevant data, concatenates and returns it as a string. 如果出于某种原因,解决关系对于模板而言太复杂,则在GalleryIndex添加一个名为tag的字段,并添加一个例行prepare_tags(self, obj)来查询相关数据,并将其连接并作为字符串返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM