2013-05-30 35 views
2

取回了具有基於country表中的一列(country_name)從數據庫中檢索的國家名單:空值與values_list

list_countries = Country.objects.values_list('country_name', flat=True).distinct() 

結果是這樣的:

[u'', u'China', u'France', u'Germany', ...] 

一些數據庫中的值爲空。如何刪除檢索到的空白,以便檢索到的country_name不爲空(cf country_name != '')?

回答

5

您可以使用Q對象,

from django.db.models import Q 
list_countries = Country.objects.filter(~Q(country_name='')).values_list('country_name', flat=True).distinct() 
+0

這對於Django來說比我的回答更習慣,對於大集合來說,過濾發生在數據庫中會更快。 – Blutack

1

您可以使用列表理解刪除零長度條目。

list_countries = [country for country in list_countries if len(country) > 0] 
1

我與除了一個變化阿德姆的答案達成一致。

from django.db.models import Q 
list_countries = Country.objects.filter(~Q(country_name='')).distinct().values_list('country_name', flat=True) 

這會比Adem的回答略好。