首页 > 解决方案 > 如何使用具有自定义属性的 django-haystack 搜索方面?

问题描述

我有一家 Django-oscar 商店,并成功安装了 Solr 4.7.2 作为搜索引擎。它适用于预定义的属性,例如 upc、title、product_class...

但是过滤其他属性不起作用。

那是我的目录/models.py:

class Product(AbstractProduct):
    video_url = models.URLField()
    co2 = models.IntegerField()
    is_public = models.BooleanField()
    test = models.TextField()

在 search_indexes.py 中,我尝试添加如下内容:

co2 = indexes.IntegerField(model_attr="co2", null=True, indexed=False)

def prepare_co2(self, obj):
        return self.apps.get_model().objects.filter(co2="2")
       # return obj.co2 etc. here I tried a lot of code, but didnt work

我还尝试复制此功能的现成代码。

有没有人有想法,怎么做?当我过滤 catalogue.products.title 时,它​​可以正常工作,但不能与 cataolgue.products.co2 (我自己补充)一起使用。

标签: pythondjangosolrdjango-haystackdjango-oscar

解决方案


您不能从准备函数中过滤对象,您只需要指定 haystack 如何访问对象字段。

from haystack import indexes
import oscar.apps.search.search_indexes as oscar_search_indexes


class ProductIndex(oscar_search_indexes.ProductIndex):
    co2 = indexes.IntegerField(null=False, indexed=True)

    def prepare_co2(self, obj):
        return obj.co2

以上应该可以工作(一旦您在更新 Solr schema.xml 后重新索引了您的产品),如果没有,请使用您收到的错误或示例数据的意外查询行为更新您的问题。


推荐阅读