Haystack indexing related model issue

2019-09-19 06:17发布


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


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)


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}}


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):
        return obj.mainparts.parts
    except Parts.DoesNotExist:
        return ""
# ...