Wizard
Wizard

Reputation: 22083

Select the latest updated comment in the template

I have such a model table

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

I'd like to select the latest updated comments in the template:

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

Is it possible to achieve this in template?

Upvotes: 1

Views: 25

Answers (1)

Mohit Solanki
Mohit Solanki

Reputation: 2130

Yes it is possible, latest comment will be

article.comment_set.latest('-date_updated')

Upvotes: 1

Related Questions