2014-06-24 47 views
1

我想添加一个字段从第二个模型到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) 
    .... 

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的部分部分将返回与颜色具有ForeignKey关系的Product

回答

2

使用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 %} 
+0

SearchIndex Api

例如。对不起,我错过了这一点。感谢您的帮助Aamir! – ajt

0

产品是否有多种颜色?如果没有,我会从'产品'模型中将FK'Color'。

按原样,您可以在您的索引中添加MultiValue字段,并使用django表单中内置助手a-la'clean_foo'的'prepare_foo'函数准备值。

详情参见文档:更新模板的伎俩

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