我想将第二个模型中的字段添加到 django-haystack 查询中。我有两个具有以下结构的模型:
class Product(models.Model):
created_date = models.DateField(auto_now_add=True)
name = models.CharField(max_length=254)
summary = models.CharField(null=True, blank=True, max_length=255)
....
class Color(models.Model):
product_color = models.CharField(max_length=256, blank=True, null=True)
created_date = models.DateField(auto_now_add=True)
slug = models.SlugField(max_length=254)
product = models.ForeignKey('Product')
我有以下 search_index.py:
from django.utils import timezone
from haystack import indexes
from .models import Product
from .models import Color
class ProductIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
def get_model(self):
return Product
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.filter(
created_date__lte=timezone.now())
如何将 Color
模型的 product_color
添加到搜索索引,以便在有人在搜索中包含 product_color
的部分内容时查询它会返回一个与颜色有外键关系的Product
?
最佳答案
使用MultiValueField
它将存储与产品相关的所有颜色:
product_colors = indexes.MultiValueField()
准备:
def prepare_product_colors(self, obj):
return [o.product_color for o in obj.color_set.all()]
并直接使用该字段按产品颜色进行过滤。或者,如果您不想在特定字段上使用搜索,而是执行自动查询,则将产品颜色附加到最终索引文本中:
def prepare(self, obj):
prepared_data = super(SlateUpIndex, self).prepare(obj)
prepared_data['text'] += ' '.join(self.prepare_product_colors(obj))
return prepared_data
无需执行上述所有操作,只需在模板中添加颜色search/indexes/{app_label}/{model_name}_{field_name}.txt
:
{% for color in object.color_set.all %}
{{ color.product_color }}
{% endfor %}
关于python - 使用 django haystack 查询第二个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24391579/