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.
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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With