1

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). 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:

 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

Q-bart
  • 1,503
  • 4
  • 22
  • 41

1 Answers1

4

Like Django's queryset Q object, django haystack has a SQ object, which allows using | 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))
)
Brobin
  • 3,241
  • 2
  • 19
  • 35