【问题标题】:Django template: Extract field from model queryset objectDjango模板:从模型查询集对象中提取字段
【发布时间】:2016-12-18 13:25:30
【问题描述】:

在 Django 模板中,我使用以下方法获取最新评论:

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

其中blogBlog 模型的一个实例,commentsrelated_nameForeignKeyComment 模型。

这相当于

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 }}

我得到一个:

无法解析余数:'.text' TemplateSyntaxError

【问题讨论】:

    标签: django django-templates django-queryset


    【解决方案1】:
    • 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) 不应该是 {% %}
    • @Jedi 已编辑。谢谢!
    【解决方案2】:

    一种方法是使用“with”:

    {% with blog.comments.all|dictsort:"created_at"|last as lastcomment %}
      {{ lastcomment.text }}
    {% endwith %}
    

    【讨论】:

      猜你喜欢
      • 2011-10-07
      • 2011-04-11
      • 2012-12-28
      • 2023-03-07
      • 1970-01-01
      • 2013-10-10
      • 2011-03-25
      • 2021-10-25
      • 2021-09-19
      相关资源
      最近更新 更多