我正在尝试对具有多对多字段的模型进行搜索,我想使用此字段过滤搜索。
这是我目前的代码:
search_indexes.py
class ListingInex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
business_name = indexes.CharField(model_attr='business_name')
category = indexes.MultiValueField(indexed=True, stored=True)
city = indexes.CharField(model_attr='city')
neighborhood= indexes.CharField(model_attr='neighborhood')
state = indexes.CharField(model_attr='state')
address = indexes.CharField(model_attr='address')
zip_code = indexes.CharField(model_attr='zip_code')
phone_number = indexes.CharField(model_attr='phone_number')
def get_model(self):
return listing
def index_queryset(self, using=None):
return self.get_model().objects.all()
def prepare_category(self, obj):
return [category.name for category in obj.category_set.all()]
listing_text.txt
{{ object.business_name }}
{{ object.state }}
{{object.city}}
{{object.zip_code}}
{{object.phone_number}}
{{object.neighborhood}}
{% for category in obj.category.all %}
{{ category.name }}
{% endfor %}
我正在尝试进行简单搜索:
search_results = SearchQuerySet().filter(category=query_text).filter
它返回一个空列表。提前谢谢。
答案 0 :(得分:2)
阅读你的代码我认为问题在于:
{% for category in obj.category.all %}
{{ category.name }}
{% endfor %}
类别不是对象,是MultiValueField。也许如果你尝试类似的东西:
{% for category in object.category.all %}
{{ category.name }}
{% endfor %}
object.category.all 而不是obj.category.all。我不确定解决方案是这样,但我很确定错误可能在这3行中。