Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve values from Django query set?

Tags:

python

django

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 %}
like image 550
ipegasus Avatar asked Jul 26 '12 22:07

ipegasus


1 Answers

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 }}
like image 156
Hassek Avatar answered Sep 30 '22 09:09

Hassek