soultaker soultaker - 7 days ago 8
Python Question

How can I filter and count objects in DJANGO template?

Hello I justa want to ask this because Im new in django, my trouble is that i want to count how many comments have a post and put it in to the html template.
But the thing is that im using for to gather all the events in the db, but i just want to show only the count of comments that have every event that the "for" are showing.
this is my models, view, and template.
Thank you so much.

MODELS

class Event(TimeStampModel):
name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(editable=False)
summary = models.TextField(max_length=255)
content = models.TextField()
category = models.ForeignKey(Category)
place = models.CharField(max_length=50)
start = models.DateTimeField()
finish = models.DateTimeField()
image = models.ImageField(upload_to = 'eventos')
is_free = models.BooleanField(default=True)
amount = models.DecimalField(max_digits=6, decimal_places=0, default=0)
views = models.PositiveIntegerField(default=0)
organizer = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)

def save(self, *args, **kwargs):
if not self.id:
self.slug = slugify(self.name)
super(Event, self).save(*args, **kwargs)

def __unicode__(self):
return self.name

class Comments(TimeStampModel):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
event = models.ForeignKey(Event)
content = models.TextField()

def __unicode__(self):
return "%s %s" % (self.user.username, self.event.name)


VIEW

class IndexView(TemplateView):
template_name = 'eventos/index.html'
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
context['events'] = Event.objects.all().order_by('-created')[:6]
context['categories'] = Category.objects.all()
context['comments'] = Comments.objects.all()
return context


HTML TEMPLATE

{% for event in events %}
<li class="span4 ">
<div class="thumbnail thumbnail-1">
<h3 class="titulo-fix" >{{ event.name }}</h3>
<img class="center-cropped" src="{{ event.image.url }}" alt="">
<section>
<a href="#"><h3>{{ event.category }} </h3></a>
<div class="meta">
<time datetime="2012-11-09" class="date-1"><i class="icon-calendar"></i> {{ event.start }}</time>
<div class="name-author"><i class="icon-user"></i> <a href="#">{{ event.organizer }}</a></div>
<a href="#" class="comments"><i class="icon-comment"></i> comments</a>
</div>
<div class="clear"></div>
<p>{{ event.place }}</p>
<a href="#" class="btn btn-1">Leer mas..</a>
</section>
</div>
</li>
{% endfor %}


I want to show it just in that part of the html where it says comments.. with a tag of course, but i just dont know wich tag or how to do it.

Answer

You can create a helper method on the model which can help you show the number of comments.

Something like this:

class Event(TimeStampModel):
    ...

    def comments_count(self):
        #Your filter criteria can go here. 
        return self.comments_set.count()

and in the comments:

{{event.comments_count}}

More documentation on the reverse lookups can be found here

If you are not filtering, as, @MadWombat mentions, you could just do

{{event.comments_set.count}}