在模板中选择最新的更新评论

时间:2018-08-05 16:44:58

标签: django

我有这样的模型表

class Comment(models.Model):
    STATUS = (
        (1,  'normal'),
        (0, 'deleted'),
    )
    owner = models.ForeignKey(User, on_delete=models.CASCADE)
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    body = models.TextField() # set the widget
    status = models.IntegerField(choices=STATUS)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('-date_created',)

    def __str__(self):
        return self.body

我想在模板中选择最新的更新评论:

{% for comment in article.comment_set.all() %}
   {% if comment.date_updated is the latest %}
       {{ comment.date_updated | timesince}}
{% endfor %}

是否可以在模板中实现?

1 个答案:

答案 0 :(得分:1)

是的,最新的评论将是

article.comment_set.latest('-date_updated')