Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deal with "None" DB values in Django queries

Tags:

python

django

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.

like image 211
givp Avatar asked Nov 28 '09 20:11

givp


2 Answers

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)
like image 142
Nick Craig-Wood Avatar answered Oct 14 '22 01:10

Nick Craig-Wood


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)
like image 3
Jochen Ritzel Avatar answered Oct 14 '22 01:10

Jochen Ritzel