简体   繁体   English

Django Haystack。 和,或在搜索查询集中

[英]Django Haystack. And, or in search queryset

Using: Haystack and Sorl. 使用:干草堆和索尔。

I need to make a search queryset to search products by filter. 我需要创建一个搜索查询集以按过滤条件搜索产品。

Firstly, I need to filter only products based on my site (Django site framework). 首先,我只需要过滤基于我的网站(Django网站框架)的产品。 So I do: 所以我做:

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

It returns such search query: 它返回这样的搜索查询:

site:(6)

OK. 好。

Then I need to filter by attributes: 然后我需要按属性过滤:

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

And it generates such query: 并生成这样的查询:

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

But, I need to make a query like this: 但是,我需要进行如下查询:

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

So I tried to change filtering by attributes to filter_or : 所以我尝试filter_or属性的过滤更改为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))

And the result is: 结果是:

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

But I need else: 但是我还需要:

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

So, how to do this? 那么,该怎么做呢? Help me, please 请帮帮我

Like Django's queryset Q object, django haystack has a SQ object, which allows using | 像Django的queryset Q对象一样,django haystack也有一个SQ对象,该对象允许使用| and & operators in filtering &运算符

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM