I'm trying to count the number of occurrences of the different product names in a table. I would like the result to be something like this:
Laptop 10
Mice 15
And so on, yet instead I get:
2 10
1 15
Any ideas what could be wrong?
This is my models.py:
class ProductNoSerial(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category)
def __str__(self):
return self.name
class ProductNoSerialInstance(models.Model):
STATUS_CHOICES = (
('in_inventory', 'In Stock'),
('given_out', 'Given Out'),
('repair', 'Repair')
)
name = models.ForeignKey(ProductNoSerial)
owner = models.ForeignKey(Employee, blank=True, null=True)
it_dep = models.ForeignKey(ItDep)
status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft')
def __unicode__(self):
return self.name
This is my view.py:
def InventoryList(request):
count_query = ProductNoSerialInstance.objects.values('name').annotate(count=models.Count('name'))
context = { 'inventory_list': count_query }
return render(request, 'inventory_list.html', context)
And finally my inventory_list.html:
<p><b>List of inventory<b></p>
<table>
{% for item in inventory_list %}
<tr>
<td> {{ item.name }} </td>
<td> {{ item.count }} </td>
</tr>
{% endfor %}
</table>
I've tried these suggestions, but without any luck. Any ideas what might be wrong? I figured the problem could be caused by the fact that name
is a ForeignKey?