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
显示所有不具有名为已销毁
和永久检索
最新状态的项目。然而,这有一个问题。
假设我的数据库中有一些项目 - 例如 item1 {in、out、destroyed}、item2 = {destroyed、in}、item3 = {permanent检索}、item4 = {}。因为它寻找最新状态,所以它会打印 {item2}。我现在想在 staock 的总项目中打印 item4 。基本上 item4 是一个没有状态的项目。但由于它尚未被销毁
或永久
检索,因此需要将其包含在列表中。但我似乎无法找到解决办法。我希望我已经把一切说清楚了。
模板
{{total_items_in_stock|length}}
I seem to have a problem trying to count. I have a list item where each item can store many statuses, although I am only interested in it's latest status only. Now look at my views.
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
shows all items which do not have a latest status called Destroyed
and Permanent Retrieval
. There is a problem with this however.
Suppose I have some items in my database - say item1 {in, out, destroyed}, item2 = {destroyed, in}, item3 = {permanent retrieve}, item4 = {}. Because it looks for the latest status, it will print {item2}. I now want to print item4 as well in the total items in staock. Basically item4 is an item without a status. But since it has not been Destroyed
or Permanent
Retrieval it needs to be included in the list. But I can't seem to find a way out of this. I hope I have made everything clear.
Template
{{total_items_in_stock|length}}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为替代方案,您可以将
in_stock
方法添加到您的StorageItem
类中。沿着这些思路:
然后你可以简化你的列表理解:
As an alternative you could add an
in_stock
-method to yourStorageItem
class.Something along these lines:
Then you could simplify your list comprehension:
试试这个:
Try this: