2

I want to do the following thing:

lets say I have:

query_terms = ["A", "B"]

And what is needed is the following query:

House.objects.filter(
    Q(name__icontains="A") | Q(building__name__icontains="A",
    Q(name__icontains="B") | Q(building__name__icontains="B"
)

I don't know how to join this "OR" statements together with "AND" having a dynamic query_terms list

1
  • what are you trying to achieve?
    – karthikr
    Commented Aug 29, 2012 at 19:14

1 Answer 1

6
full_query = None
for query in query_terms:
    q = Q(name__icontains=query) | Q(building__name__icontains=query)
    if full_query is None:
        full_query = q
    else:
        full_query = full_query & q

I'm probably not optimizing this exactly right, but something along these lines should work.

1
  • Excelent, as soon as I can, I'll give the the tick! Thanks you so much
    – fceruti
    Commented Aug 29, 2012 at 19:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.