2017-05-25 85 views
1

在過濾值列表時,有沒有包含None的方法?可能包含無的Django過濾器

>>> MyModel.objects.filter(amount=10).count() 
9 
>>> MyModel.objects.filter(amount=None).count() 
30 
>>> MyModel.objects.filter(amount__in=[10]).count() 
9 
>>> MyModel.objects.filter(amount__in=[None, 10]).count() 
9 

我希望最後調用返回39,而不是9

在我的實際使用情況無可能或可能不包括在值列表進行過濾的。我可以使用if/else塊在值列表中檢查None,並根據需要使用Q對象構建查詢,但是爲大量篩選器執行此操作會變得很糟糕。必須有更好的方式,對吧?

回答

2

我想你會需要用Q對象,可能這種方式將不會是一個爛攤子:

MyModel.objects.filter(Q(amount__isnull=True) | Q(amount__in=the_list)).count() 

並且只包括第一部分,如果None是在列表...

或者類似的東西:

query = Q(amount__in=the_list) 
if None in the_list: 
    query |= Q(amount__isnull=True) 

MyModel.objects.filter(query).count() 

不知道是否有一個更好的辦法。

+0

我不知道'''| ='''語法,所以至少這會有所幫助。 – rurp