How to work with None DB values ​​in Django queries

I have the following filter query that executes an SQL OR statement:

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

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

Cannot use None as request value

Is there an elegant way to check if filter values ​​are cleared before creating an OR filter request?

Many thanks.

+7
python django
source share
2 answers

You can do this, which is easy to generalize to more queries.

 query = Q() for search in (prefs.address1, prefs.address2): if search: query |= Q(title__icontains=search) results = Stores.objects.filter(query) 
+10
source share

It?

 thefilter = Q(title__icontains=prefs.address1) if prefs.address2 is not None: thefilter = thefilter | Q(title__icontains=prefs.address2) results = Stores.objects.filter( thefilter) 
+3
source share

All Articles