1

使用:Haystack 和 Sorl。

我需要创建一个搜索查询集来按过滤器搜索产品。

首先,我只需要根据我的网站(Django 网站框架)过滤产品。所以我这样做:

sqs = sqs.filter(site=site.pk)

它返回这样的搜索查询:

site:(6)

好的。

然后我需要按属性过滤:

sqs = sqs.filter(attribute_codes='power', attribute_values__range=(20, 30))
sqs = sqs.filter(attribute_codes='power', attribute_values__range=(40, 50))

它会生成这样的查询:

(site:(6) AND attribute_codes:(power) AND attribute_values:(["20" TO "30"]) AND attribute_values:(["40" TO "50"]))

但是,我需要进行这样的查询:

(site=6) AND ((attributes1) OR (attributes2))

所以我尝试将按属性过滤更改为filter_or

 sqs = sqs.filter_or(attribute_codes='power', attribute_values__range=(20, 30))
sqs = sqs.filter_or(attribute_codes='power', attribute_values__range=(40, 50))

结果是:

(site:(6) OR (attribute_codes:(power) AND attribute_values:(["20" TO "30"])) OR (attribute_codes:(power) AND attribute_values:(["40" TO "50"])))

但我还需要:

    (site=6) AND ((attributes1) OR (attributes2))

那么,如何做到这一点呢?请帮帮我

4

1 回答 1

4

和 Django 的 querysetQ对象一样,django haystack 有一个SQ对象,它允许在过滤中使用|和运算符&

sqs = sqs.filter(site=6)
sqs = sqs.filter(SQ(attribute_codes='power') | SQ(attribute_values__range=(20, 30))

或者

sqs = sqs.filter(
    SQ(site=6) & (SQ(attribute_codes='power') | SQ(attribute_values__range=(20, 30))
)
于 2017-06-06T19:24:58.247 回答