模板中Django注释的值 [英] Django annotated value in template

查看:63
本文介绍了模板中Django注释的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以访问模板中查询集上的注释值?

Is it possible to access annotated values on querysets in templates?

例如,我将以下查询集传递给模板:

For example I have the following queryset that I'm passing to my template:

context[videos] = Videos.objects.annotate(view_count=Count(views)).order_by(view_count)[:100]

在我的模板中,我试图像这样获得视图计数:

In my template I'm trying to get the view count like this:

{% for video in videos %}
  {{ video.view_count }}
{% endfor %}

什么都不显示。

但是我使用:

{{ video.views.count }}

似乎不错-但我相信第二个选项会重新计算视图计数。我想使用带注释的值,因为它应该已经计算了。

It seems fine - but i believe the second option recalculates the view count. I'd like to use the annotated value since it should already be calculated.

推荐答案

每个项目的QuerySet聚合方法,注释() ,之所以这样命名,是因为它像普通字段一样注释(设置)到它产生的每个 item (模型实例)的汇总值,例如:

It would make sense that the QuerySet aggregation method per-item, annotate(), has such a name because it annotates (sets) the aggregated value to each item (model instance) it yields, like a normal field, for example:

# Build an annotated queryset
>>> q = Book.objects.annotate(Count('authors'))
# Interrogate the first object in the queryset
>>> q[0]
<Book: The Definitive Guide to Django>
>>> q[0].authors__count
2
# Interrogate the second object in the queryset
>>> q[1]
<Book: Practical Django Projects>
>>> q[1].authors__count
1

关于名称:


批注的名称自动从聚合函数的名称和要聚合的字段的名称派生。指定注解时,可以通过提供别名来覆盖此默认名称。

the name for the annotation is automatically derived from the name of the aggregate function and the name of the field being aggregated. You can override this default name by providing an alias when you specify the annotation:



>>> q = Book.objects.annotate(num_authors=Count('authors'))
>>> q[0].num_authors
2
>>> q[1].num_authors
1

例如:

context['videos'] = Videos.objects.annotate(view_count=Count('views')).order_by('-view_count')[100:]

您可以使用:

[video.view_count for video in context['videos']]

应该是与 values_list()相同 a>:

Which should be the same as using values_list():

Videos.objects.annotate(view_count=Count('views')).values_list('view_count', flat=True)

类似于以下内容:

{% for video in videos %}
    {{ video.view_count }}
{% endfor %}

说,与普通字段不同过滤器的排列顺序已申请事项,您已经被警告B)

That said, unlike normal fields, the order in which filters are applied matters, you've been warned B)

这篇关于模板中Django注释的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆