8

I would like to know how to get the values in a template, from a variable called 'my_movie_code_count':

my_movie_code_count = Code.objects.values('movie__title').annotate(Count('movie'))

If I do a pprint to the console I get:

for m in my_movie_code_count:
    pprint.pprint(m)

console output:

{'movie__count': 1, 'movie__title': u'THE MEN WHO STARE AT GOATS'}
{'movie__count': 3, 'movie__title': u'PIRATE RADIO'}
{'movie__count': 1, 'movie__title': u'A SERIOUS MAN'}
{'movie__count': 3, 'movie__title': u'GREENBERG'}
{'movie__count': 1, 'movie__title': u'MILK'}
{'movie__count': 1, 'movie__title': u'TEST'}

template: (Currently it doesn't show any output.)

    {% for movie in my_movie_code_count %}
    {{movie.title}}:{{movie.count}}
    {% endfor %}
1
  • I wanted to do something different and just print the whole queryset to console with quickest solution print(YourModl.objects.all().values()). Doesn't solve your problem but this was the only related question that came up. Commented Dec 17, 2017 at 18:20

1 Answer 1

5

my_movie_code_count[0].movie__count now I know this is not exactly wanted so you could add a name to the annotation:

my_movie_code_count = Code.objects.values('movie__title').annotate(num=Count('movie'))
print my_movie_code_count[0].num
1

you can check the docs here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#annotate

Also it doesn't shows anything because django fails silently on templates (so a designer doesn't break a whole page). If you check the attributes, their names are movie__title and movie__count so you would have to change the template attributes to:

{{ movie.movie__title }}: {{ movie.movie__count }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.