[英]Django query: Want to count an empty value
我似乎很難計數。 我有一個列表項,其中每個項可以存儲許多狀態,盡管我僅對它的最新狀態感興趣。 現在看看我的看法。
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
顯示了沒有最新的狀態召集所有物品Destroyed
和Permanent Retrieval
。 但是,這有一個問題。
假設我的數據庫中有一些項目-例如item1 {in,out,destroy},item2 = {destroyed,in},item3 = {永久檢索},item4 = {}。 因為它會尋找最新狀態,所以它將打印{item2}。 我現在想在staock的總項目中也打印item4。 基本上item4是沒有狀態的項目。 但由於尚未Destroyed
或Permanent
檢索,因此需要將其包括在列表中。 但是我似乎找不到解決辦法。 我希望我已經把一切都弄清楚了。
模板
{{total_items_in_stock|length}}
嘗試這個:
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']]
或者,您可以在StorageItem
類中添加in_stock
方法。
遵循以下原則:
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()]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.