tags:

views:

72

answers:

2

Hello,

I have the following filter query which is doing an SQL OR statement:

results = Stores.objects.filter(Q(title__icontains=prefs.address1) | Q(title__icontains=prefs.address2))

This works fine but if the prefs.address1 and prefs.address2 values (which come from another model) are blank in mySQL, Django complains with the following error:

Cannot use None as a query value

Is there an elegant way to check to see if my filter values are not blank before constructing the OR filter query?

Many thanks.

+2  A: 

This?

thefilter = Q(title__icontains=prefs.address1)
if prefs.address2 is not None:
    thefilter = thefilter | Q(title__icontains=prefs.address2)
results = Stores.objects.filter( thefilter)
THC4k
prefect. thank you. sorry for n00b question :)
givp
A: 

You could do this which is easily generalisable to more queries

query = Q()
for search in (prefs.address1, prefs.address2):
    if search:
        query |= Q(title__icontains=search)
results = Stores.objects.filter(query)
Nick Craig-Wood
oh this is even nicer. thank you.
givp