简体   繁体   中英

Django query: Want to count a set in template

I have a list of item which only displays the latest status of each item. What I want to do now is count. Problem is that is the count function will only work properly if latest is removed - however that would give me something like this.

item1=1 item2=33 item3=12 item4=0

Basically it will count all statuses for that item, but it needs focus on counting the latest status so the answer in this case should be 3. This is why I need the latest latest . There is also a foreign key relationship between a storage item and status, an item can have many statuses or if not, no status at all.

#views.py
client = models.Client.objects.get(pk = client_id)
items = client.storageitem_set.all()

template

{% for item in items %}
        {{item.itemstatushistory_set.latest}}
{% endfor %}

Seems to me that all you need is the count of all items that have a status - rather than the count of all statuses related to your items. Is that right? If so, this will do it:

count = models.StorageItem.objects.filter(client=client_id, itemstatushistory__isnull=False).count()

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