开发者

Django Want to count different item types

开发者 https://www.devze.com 2023-03-07 14:26 出处:网络
Previously I had a client summary list in a table. In one column I had a list of object types and in another, I had the quantity of that object type.

Previously I had a client summary list in a table. In one column I had a list of object types and in another, I had the quantity of that object type.

@login_required
def client_summary(request, client_id):
    client = models.Client.objects.get(pk = client_id)
    items = client.storageitem_set.all()
    tape_and_film_items = client.storageitem_set.filter(type="1")
    total_tape_and_film_items = tape_and_film_items.count()
    electrical_equipment_items = client.storageitem_set.filter(type="2")
    total_electrical_equipment_items = electrical_equipment_items.count()
    storage_office_equipment_items = client.storageitem_set.filter(type="3")
    total_storage_office_equipment_items = storage_office_equipment_items.count()


<table cellspacing="15" style="float: left">
<tr><th scope="col">Type</th><th scope="col">Quantity</th></tr>
</tr><td>Tape + Film</td><td align="c开发者_Python百科enter">{{total_tape_and_film_items}}</td></tr>
</tr><td>Electrical Equipment</td><td align="center">{{total_electrical_equipment_items}}</td></tr>
</tr><td>Storage Office Equipment</td><td align="center">{{total_storage_office_equipment_items}}</td></tr>
</table>

Now this would work, but there is a problem. I did not knew earlier that users could add their own storage object from a form in my web app. If they try add a new object type, it will not show up in my client summary unless I explicitly write up an django query in a view passing a variable in a template. If there was no form to add an object type, this would have worked.

So in my template now I have this now in the type column. This part will work because all I really need to do is list all the storage item objects regardless of whoever client it is.

views.py

item_type = models.StorageObject.objects.all()

template

 {% for item in item_type %}
     {{item.title}}
 {% endfor %}

But in the quantity column I can't seem to count. Returns nothing.

{% for item in items %}
    {{item.type.count}}
{% endfor %}


If you need to display some info of items for every tag, you can use regroup tag. If you want only quantity, use Count aggregation function.

0

精彩评论

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