问题
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