Django query:要计算空值吗

2024-06-01 02:24:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在数数的时候好像有问题。我有一个列表项,其中每个项可以存储许多状态,尽管我只对它的最新状态感兴趣。现在看看我的观点。在

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={destroyed,in},item3={permanently retrieve},item4={}。因为它查找最新状态,所以它将打印{item2}。我现在想在staock中打印item4。基本上item4是一个没有状态的项。但是由于它还没有DestroyedPermanent检索,所以需要将其包含在列表中。但我似乎找不到一条出路。我希望我已经把一切都说清楚了。在

模板

^{pr2}$

Tags: inclient列表状态stockitemsstorageitem
2条回答

另一种方法是将in_stock-方法添加到StorageItem类中。在

大致如下:

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

这样你就可以简化你对清单的理解:

^{pr2}$

试试这个:

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']]

相关问题 更多 >