2011-04-06 59 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