如何在DJANGO模板中过滤和计算对象?

时间:2016-11-30 20:37:58

标签: python django function class models

您好我想问这个因为我是django中的新手,我的麻烦在于我想要计算有多少评论有帖子并将其放入html模板中。 但事实是,我正在使用收集数据库中的所有事件,但我只想显示每个事件的评论数量" for"正在显示。 这是我的模型,视图和模板。 非常感谢你。

模型

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)  

查看

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模板

{% 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 %}

我想在html的那个部分显示它所说的评论..当然还有一个标签,但我只是不知道这个标签或者怎么做。

1 个答案:

答案 0 :(得分:3)

您可以在模型上创建一个帮助器方法,它可以帮助您显示注释的数量。

这样的事情:

class Event(TimeStampModel):
    ...

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

并在评论中:

{{event.comments_count}}

More documentation on the reverse lookups can be found here

如果你没有过滤,就像@MadWombat提到的那样,你可以做到

{{event.comments_set.count}}