Django 模板:从模型查询集对象中提取字段
Django template: Extract field from model queryset object
在 Django 模板中,我正在使用以下方法获取最新评论:
{{ blog.comments.all|dictsort:"created_at"|last }}
其中 blog
是 Blog
模型的实例,comments
是 related_name
与 ForeignKey
到 Comment
模型.
这相当于
blog.comments.all().order_by("created_at").last()
问题:如何获取模板中评论的text
字段?
在视图中我可以使用:
blog.comments.all().order_by("created_at").last().text
如果我尝试:
{{ blog.comments.all|dictsort:"created_at"|last.text }}
我得到一个:
Could not parse the remainder: '.text' TemplateSyntaxError
with
标签:
{% with newest_comment=blog.comments.all|dictsort:"created_at"|last %}
{{ newest_comment.text }}
{% endwith %}
cached_property
装饰者:
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['newest_comment'] = blog.comments.order_by('created_at').last()
return render(request, template, context)
latest()
方法:
models.py
class Comment(models.Model):
class Meta:
get_latest_by = 'created_at'
template.html
{{ blog.comments.latest.text }}
一种方法是使用 "with":
{% with blog.comments.all|dictsort:"created_at"|last as lastcomment %}
{{ lastcomment.text }}
{% endwith %}
在 Django 模板中,我正在使用以下方法获取最新评论:
{{ blog.comments.all|dictsort:"created_at"|last }}
其中 blog
是 Blog
模型的实例,comments
是 related_name
与 ForeignKey
到 Comment
模型.
这相当于
blog.comments.all().order_by("created_at").last()
问题:如何获取模板中评论的text
字段?
在视图中我可以使用:
blog.comments.all().order_by("created_at").last().text
如果我尝试:
{{ blog.comments.all|dictsort:"created_at"|last.text }}
我得到一个:
Could not parse the remainder: '.text' TemplateSyntaxError
with
标签:{% with newest_comment=blog.comments.all|dictsort:"created_at"|last %} {{ newest_comment.text }} {% endwith %}
cached_property
装饰者: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['newest_comment'] = blog.comments.order_by('created_at').last() return render(request, template, context)
latest()
方法:models.py
class Comment(models.Model): class Meta: get_latest_by = 'created_at'
template.html
{{ blog.comments.latest.text }}
一种方法是使用 "with":
{% with blog.comments.all|dictsort:"created_at"|last as lastcomment %}
{{ lastcomment.text }}
{% endwith %}