Django template: extract the field from the queryset object of the template


In a Django template, I am fetching the newest comment using:

{{ blog.comments.all|dictsort:"created_at"|last }}

where blog is a instance of the Blog model, comments is the related_name with a ForeignKey to the Comment model.

This is the equivalent of


Question: How can I get the text field for the comment in the template?

In the view I can do this using:


If I try:

{{ blog.comments.all|dictsort:"created_at"|last.text }}

I get a:

Could not parse the remainder: '.text' TemplateSyntaxError

  • with tag:

    {% with newest_comment=blog.comments.all|dictsort:"created_at"|last %}
        {{ newest_comment.text }}
    {% endwith %}
  • cached_property decorator:

    from django.utils.functional import cached_property
    class Blog(models.Model):
        def newest_comment(self):
            return self.comments.order_by('created_at').last()


    {{ blog.newest_comment.text }}
  • context:

    context['newest_comment'] = blog.comments.order_by('created_at').last()
    return render(request, template, context)
  • latest() method:

    class Comment(models.Model):
        class Meta:
            get_latest_by = 'created_at'


    {{ blog.comments.latest.text }}