Reputation: 186762
TEMPLATE:
<ul id="bugs-list">
{% for group in groups %}
<h2>{{ group.name }}</h2> <span></span>
{% for data in group.grab_bugs %}
<li><a href="{{data.get_absolute_url}}">{{data.name }}</a></li>
{% endfor %}
{% endfor %}
</ul>
models.py:
class BrowserGroups( models.Model ):
name = models.CharField( max_length=100 )
slug = models.SlugField(unique=True)
browsers = models.ManyToManyField( 'Browser' )
def grab_bugs(self):
bugs = Bug.objects.filter(browser__browsergroups=self,really_bug=True).distinct()
return bugs
def __unicode__(self):
return self.name
class Meta:
verbose_name_plural = 'Browser Groups'
I'm trying to render the number of bugs (data
) near the <h2>
. What would be an efficient way of including the count of data
near the h2? Should I define a separate function in my model class to return the total # of bugs? Or is there a more efficient way?
Upvotes: 2
Views: 250
Reputation: 74795
{% with group.grab_bugs as distinct_bugs %}
<h2>{{ group.name }}</h2> (Count: {{ distinct_bugs.count }})
{% for data in distinct_bugs %}
<li><a href="{{data.get_absolute_url}}">{{data.name }}</a></li>
{% endfor %}
{% endwith %}
Explanation: the grab_bugs
method of the Group
class returns a querset of Bug
instances. To get a count of the bugs invoke the count()
method on the queryset.
This will cost you two queries (not counting the ones inside the loop). One to get the count and then next to retrieve a list of bugs.
Upvotes: 2