0

I'm trying to build a query form in which user can encoded keywords. The result must show the offer that match the keyword following an "exclusive and". Therefore I use the Q module.

The keywords are split into a list and a loop is performed so I can build the query to be executed. But I somehow misunderstood something as it doesn't work at all.

Here is the code:

            sentence = "Offer.objects.filter("
            kw_list = keywords.split()
            #kw_count = len(kw_list) could be useful if I perform a while loop

            for kw in kw_list:
                sentence += "Q(content__contains="+ kw +") & "

            results = sentence + ")"
Cobblepot
  • 59
  • 10
  • 2
    ....I feel like you want something like `reduce(operator.and_, (Q(content__contains=kw) for kw in kw_list), Q())` – NightShadeQueen Sep 01 '15 at 19:49
  • 2
    What is an "exclusive and"? We talk about "exclusive or" vs "inclusive or" to distinguish cases where we care if _both_ truth-values are the same (since 'or' only cares about one), but based on the way 'and' works I see no such parallel. – Two-Bit Alchemist Sep 01 '15 at 19:51
  • You are building a string. Even if it looked exactly like the query you want to run, you'd still have to evaluate it. But there are better ways, as NightShadeQueen hinted. – Paulo Almeida Sep 01 '15 at 20:02

1 Answers1

1

Since my reputation is to low to add a comment, i post this as answer. I think this question gives you some answers to your problem.

How to dynamically compose an OR query filter in Django?

Community
  • 1
  • 1
BigZ
  • 836
  • 8
  • 19