On Wed, Feb 22, 2012 at 01:15:04PM -0800, gowthaman ramasamy wrote:
I am trying to construct the following query at the end.
Result.objects.filter(Q(analysis__experiment__experiment_code="PyLS24")
|Q(analysis__experiment__experiment_code="PyLS40"))

How I do now:
The values are passed from a from(post) using checkboxes (#expcodes =
request.POST.getlist('expcode')
). So I get a list of:
expcodes = ['PyLS24', 'PyLS40']
then use the for loop to construct string representation of Q object.
expcodes = ['PyLS24', 'PyLS40']
k=''
c=0
for e in expcodes:
j=e.join(['Q(analysis__experiment__experiment_code="','") '])
if c == 0:
k = j
else:
k='|'.join([k, j])
c = c+1

k in this gives me 'Q(analysis__experiment__experiment_code="PyLS24")
|Q(analysis__experiment__experiment_code="PyLS40")  '.
When i use this to query the model as following... Result.objects.filter(k)I get 
"ValueError: too many values to unpack" error. But, exact string, if
I copy paste into Results.object.filter(here) it works.

When I checked the type, k constructed from for loop is in string format
(obviously). But, when I copy paste the pint out of k, it automatically
becomes Django's Q object.

The issue is that you can't use a string to generate the Q object passed to filter(). Instead, you need to build them up in a list, and then use the bitwise-OR operator. You can either do that in a loop, or this way:

import operator

q_objs = [ Q(analysis__experiment__experiment_code=code) for code in expcodes ]
arg = reduce(operator.or_, q_objs)  # do bitwise-OR of all objects in the list
Results.object.filter(arg)

--
You received this message because you are subscribed to the Google Groups "Django 
users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to