如何在Django查询中处理“无”DB值

时间:2022-12-25 13:50:47

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

我有以下过滤器查询正在执行SQL OR语句:

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:

这工作正常,但如果prefs.address1和prefs.address2值(来自另一个模型)在mySQL中是空白的,Django会抱怨以下错误:

Cannot use None as a query value

不能使用None作为查询值

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

在构造OR过滤器查询之前,是否有一种优雅的方法来检查我的过滤器值是否为空?

Many thanks.

非常感谢。

2 个解决方案

#1


10  

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)

#2


3  

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)

#1


10  

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)

#2


3  

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)