Haystack indexing related model issue

血红的双手。 提交于 2020-01-07 00:07:51

问题


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

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

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

and main_text.txt:

{{ object.parts}}

回答1:


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 ""
# ...


来源:https://stackoverflow.com/questions/20878754/haystack-indexing-related-model-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!