Thursday, August 25, 2011

Re: search with a optional value

On 08/16/2011 03:20 PM, john wrote:
> hi,
> i have a form with few fields as optional,i.e can be left blank,
> i want to search my db for values i receive from this form, how should
> i go on about writing my filters when some of values can be " ".
> any reference is kindly appreciated
>

I had to do that for a good while back and I used following approach:

# Add "or contains" query for every nonempty value in form data.
q = Q()
for k,v in form.cleaned_data.items():
if v:
q |= Q(**{k + '__contains' : v})

# Get resultset
r = MyModel.objects.filter(q);

--

Jani Tiainen

--
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+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment