Annotated Django value in a template

Is it possible to access annotated values ​​in queries in templates?

For example, I have the following request that I pass to my template:

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

In my template, I am trying to count the number of views as follows:

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

What is not displayed.

However, if I use:

{{ video.views.count }}

It seems good, but I think the second option recounts the number of views. I would like to use an annotated value, since it should already be calculated.

+5
source share
1 answer

, QuerySet , (), () ( ), , , :

# 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

:

. , :

>>> 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():

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

:

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

, , , ,, )

+2

All Articles