简体   繁体   中英

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 = 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}}

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

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()]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM