簡體   English   中英

用Django Haystack查詢第二個模型

[英]Querying a second model with 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

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

產品是否有多種顏色? 如果沒有,我將FK從“產品”模型轉換為“顏色”。

照原樣,您可以將MultiValue Field添加到索引中,並使用'prepare_foo'函數准備值,該函數是django形式的內置輔助函數a-la'clean_foo'。

有關更多信息,請參閱文檔: SearchIndex Api

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM