2012-01-26 100 views
0

有沒有辦法用django查詢在單行中執行以下操作?使用查詢而不是for循環

providers_with_no_contacts = [] 
for provider in Provider.objects.all(): 
    if not provider.userprofile_set.all(): 
     provider_with_no_contacts.append(provider) 

還是比這更好的方法?

providers_with_no_contacts = [provider for provider in Provider.objects.all() 
           if not provider.userprofile_set.all()] 

回答

1
Provider.objects.filter(userprofile__isnull=True) 
0

providers_with_no_contacts = Provider.objects.filter(userprofile_set=None)

+0

這是刻着真棒。 – Brandon

+0

這沒有奏效。也許是因爲'userprofile'是一個M2M領域? – David542

+3

嘗試:'.filter(userprofile__isnull = True)'。適用於該領域是外鍵還是M2M。 –