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
blog.comments.all().order_by("created_at").last()
Question: How can I get the text
field for the comment in the template?
In the view I can do this using:
blog.comments.all().order_by("created_at").last().text
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:models.py
from django.utils.functional import cached_property class Blog(models.Model): @cached_property def newest_comment(self): return self.comments.order_by('created_at').last()
template.html
{{ blog.newest_comment.text }}
context:
context['newest_comment'] = blog.comments.order_by('created_at').last() return render(request, template, context)
latest()
method:models.py
class Comment(models.Model): class Meta: get_latest_by = 'created_at'
template.html
{{ blog.comments.latest.text }}