reverse many to many fields in Django + count them
- by cleliodpaula
I'm trying to figure out how to solve this
class Item(models.Model):
type = models.ForeignKey(Type)
name = models.CharField(max_lenght = 10)
...
class List(models.Model):
items = models.ManyToManyField(Item)
...
I want to count how many an Item appears in another Lists, and show on template.
view
def items_by_list(request, id_):
list = List.objects.get(id = id_)
qr = list.items.all()
#NOT TESTED
num = []
i = 0
for item in qr:
num[i] = List.objects.filter(items__id = item__id ).count()
#FINISH NOT TESTED
c = {}
c.update(csrf(request))
c = {'request':request, 'list' : qr, 'num' : num}
return render_to_response('items_by_list.html', c, context_instance=RequestContext(request))
template
{% for dia in list %}
<div class="span4" >
<div>
<h6 style="color: #9937d8">{{item.type.description}}</h6>
<small style="color: #b2e300">{{ item.name }}</small>
<small style="color: #b2e300">{{COUNT HOW MANY TIMES THE ITEM APPEAR ON OTHER LISTS}}</small>
</div>
{% endfor %}
This seems to be easy, but I could not implement yet.
If anyone has some glue to me, please help me.
Thanks in advance.