干草堆索引相关模型问题 [英] Haystack indexing related model issue

查看:328
本文介绍了干草堆索引相关模型问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为两个模型准备索引,因此我可以从两个模型中搜索文本。以下是我的代码。当我运行python manage.py rebuild_index时,我得到索引行return obj.mainparts.parts的错误raise self.related.model.DoesNotExist。

I want to prepare an index for two models, so I can search text from both models. Below is my code. When I run "python manage.py rebuild_index" I get the error "raise self.related.model.DoesNotExist" for the index line "return obj.mainparts.parts".

models.py

models.py

class Main(models.Model):
    ....#various fields

class Parts(models.Model):
    main = models.OneToOneField(Main, primary_key=True, related_name='mainparts')
    parts = models.TextField(blank=True)

search_indexes.py

search_indexes.py

class MainIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    ....#various fields from class Main
    parts = indexes.CharField()

    def prepare_parts(self, obj):
        return obj.mainparts.parts

    def get_model(self):
        return Main

和main_text.txt:

and main_text.txt:

{{ object.parts}}


推荐答案

self.related.model.DoesNotExist 表示没有部件 haystack在出错时索引的 Main 对象的实例。在这种情况下,你可以捕获异常并返回一个空字符串

self.related.model.DoesNotExist means that there is no Parts instance for the Main object that haystack is indexing at the time of the error. You can catch the exception and just return an empty string "" in that case:

# ...
def prepare_parts(self, obj):
    try:
        return obj.mainparts.parts
    except Parts.DoesNotExist:
        return ""
# ...

这篇关于干草堆索引相关模型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆