开发者

Django query: Want to count an empty value

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 = StorageI开发者_JAVA百科tem.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}}


As an alternative you could add an in_stock-method to your StorageItem class.

Something along these lines:

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

Then you could simplify your list comprehension:

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


Try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜