ytjohn
ytjohn

Reputation: 197

How can I build a query in django using an iterator?

How can I build a complex query in django using an iterator? Actually, I feel this could be more of "basic python" than django, but it's got me stumped.

Essentially, I want to take a list object and generate the equivalent of this:

SELECT FROM examples WHERE mystuff LIKE 'EX1' OR mystuff LIKE 'EX2';

Here's some sample code from my attempts.

from example.models import Examples
from django.db.models import Q

includes = ['EX1', 'EX2']

conditions = []
# I can do something like this, which does build a list of objects
for ex in excludes:
    conditions.append(~Q(fullblock_icontains='%s' % ex))

# print conditions
# [<django.db.models.query_utils.Q object at 0x03557AB0>, 
# <django.db.models.query_utils.Q object at 0x03557AD0>]

# then I need to do something like this, but obviously this won't work.
blocks = Examples.objects.filter('|'.split(conditions)) 

Also, I will want to do the same thing, but negatively (~Q). I figure once we work out the LIKE, the NOT LIKE will become apparent.

Upvotes: 0

Views: 453

Answers (2)

okm
okm

Reputation: 23871

Check the doc for generating OR clause

To chain Qs together, try operator.or_

import operator
blocks = Examples.objects.filter(reduce(operator.or_, conditions))
# which works as
blocks = Examples.objects.filter(conditions[0]|conditions[1]|...)

Upvotes: 1

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53998

import operator
qobjects = [ ~Q(...), Q(...), Q(...) ]
f = reduce(operator.or_, qobjects)
Examples.objects.filter(*f)

Upvotes: 4

Related Questions