2014-06-24 46 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()]