elasticsearch,django-haystack,Python,Django,elasticsearch,Django Haystack" /> elasticsearch,django-haystack,Python,Django,elasticsearch,Django Haystack" />

Python 使用django haystack查询第二个模型

Python 使用django haystack查询第二个模型,python,django,elasticsearch,django-haystack,Python,Django,elasticsearch,Django Haystack,我想将第二个模型中的字段添加到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)

我想将第二个模型中的字段添加到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())

如何将
颜色
模型的
产品颜色
添加到搜索索引中,以便如果有人在搜索查询中包含
产品颜色
的一部分,它将返回与颜色有外键关系的
产品

使用将存储所有颜色的
多值字段
与产品关联:

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/index/{app_label}/{model_name}{field_name}.txt
中添加颜色,而不必执行上述所有操作:

{% for color in object.color_set.all %}
    {{ color.product_color }}
{% endfor %}

产品有多种颜色吗?如果没有,我会从“产品”模型中选择“颜色”

实际上,您可以向索引中添加一个多值字段,并使用“prepare\u foo”函数准备值,该函数是django表单中的内置助手a-la“clean\u foo”

有关更多信息,请参阅文档:

例如:

colors = indexes.MultValueField()
def prepare_colors(self, obj):
    return [color.product_color for color in obj.color_set.all()]

更新模板成功了。很抱歉我错过了这个。谢谢你的帮助,阿米尔!