我有一个模型与各种不同的字段类型,我希望Algolia搜索引擎索引正确。到目前为止,我已经能够非常直接地处理models.char_fields
了-我现在在想,什么是索引各种其他字段类型(例如,ForeignKey
“对象”、ImageFields
、DateTime
字段等)的最好方法。
我注意到的一件事是,Algolia会以Unix标准time...so的形式获取并存储一个DateTimeField
,最初我以为我可以使用{% humanize %}
在模板上呈现一些人类可读的东西,但没有成功。
我想知道是否有人知道从模型中拖出有用信息的方法-我的一个想法是在视图中获取对象,然后为每个返回的对象提供唯一的标识,然后执行一些条件流将该唯一标识与模型相结合,这样我就可以正常地使用该模型了……?例如:
def instant_search(request):
posts = Post.published.all()
context = {
'appID': settings.ALGOLIA['APPLICATION_ID'],
'searchKey': settings.ALGOLIA['SEARCH_API_KEY'],
'indexName': get_adapter(Post).index_name,
'posts': posts,
}
return render(request, 'blog/frame/instant_search.html', context)
在模板中,我可以使用{% for posts in post %} {% if post.id = _highlightResult.id.value %} ...do some stuff {% endif %} {% endfor %}
如果这还不够快(我几乎保证不会),我想知道Algolia是否可以处理关键信息,例如拖出在模型中定义为ImageField
的图像的url,例如,就像我在模板中使用post.image.url
或从模型中的DateTime
字段models.DateTimeField(default=timezone.now)
中获取人类可读的值一样。当Algolia索引定义的模型字段时,这样做真的很好……
发布于 2017-06-20 22:01:57
刚刚弄明白了这一点:
在models.py
中,我必须定义属性方法来获得一个经过处理的定制值,以便Algolia能够理解:
例如,我在要索引的模型的类中定义了以下内容:
def image_url(self):
"""Get upload_to path specific to this photo: Algolia recognizable format."""
return self.image_scroll_1.url
def published_date(self):
"""Returns a humanized date format for Algolia indexing."""
humanized_published_date = str(self.publish.strftime("%A, %d, %B %Y %I:%M%p"))
return humanized_published_date
希望这能帮助其他正在使用Algolia并编写各种教程的人(我以Django为例)。
然后可以在index.py中引用它们,如下所示:
从algoliasearch_django导入AlgoliaIndex
class PostIndex(AlgoliaIndex):
fields = ('title', 'post_author', 'lead_in', 'published_date', 'keyword_tags', 'image_url', 'get_absolute_url')
以及您可能喜欢的任何其他可选参数。
https://stackoverflow.com/questions/44663401
复制相似问题