2011-04-06 89 views
0

我似乎有一個問題,試圖數數。我有一個列表項,其中每個項目可以存儲多個狀態,但我只關心它的最新狀態。現在看看我的看法。Django查詢:要計算一個空值

storage_items = StorageItem.objects\ 
       .filter(client=client_id,itemstatushistory__isnull=False)\ 
       .distinct() 

total_items_in_stock = [item for item in storage_items \ 
         if item.itemstatushistory_set.latest().status.description \ 
         not in ['Destroyed','Permanent Retrieval']] 

total_items_in_stock顯示了沒有最新的狀態稱爲DestroyedPermanent Retrieval所有項目。然而,這有一個問題。

假設我在我的數據庫中有一些項目 - 說item1 {in,out,destroyed},item2 = {destroy,in},item3 = {永久檢索},item4 = {}。因爲它查找最新狀態,所以會打印{item2}。我現在要打印item4以及staock中的總項目。基本上item4是一個沒有狀態的項目。但由於它不是DestroyedPermanent檢索它需要包括在列表中。但我似乎無法找到解決辦法。我希望我已經明確了一切。

模板

{{total_items_in_stock|length}} 

回答

0

作爲替代,你可以一個in_stock - 方法添加到您的StorageItem類。沿着這些線路

東西:

def in_stock(self): 
    if 'destroyed' and 'permanent_retrieval' not in self.itemstatushistory_set.latest().status.description: 
     return True 

然後,你可以簡化您的列表理解:

total_items_in_stock = [item for item in storage_items if item.in_stock()] 
0

試試這個:

storage_items = models.StorageItem.objects.filter(client=client_id).distinct() 

total_items_in_stock = [item for item in storage_items 
     if not item.itemstatushistory_set.exists() or 
      item.itemstatushistory_set.latest().status.description not in ['Destroyed','Permanent Retrieval']] 
+0

似乎越來越對部分因故無效的語法,可以定義'total_items_in_stock' – Shehzad009 2011-04-06 11:22:00