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?
Explanation: the
grab_bugsmethod of theGroupclass returns a querset ofBuginstances. To get a count of the bugs invoke thecount()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.