简体   繁体   English

如何从Django查询集中检索值?

[英]How to retrieve values from Django query set?

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'的变量中获取模板中的值:

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

If I do a pprint to the console I get: 如果我对控制台执行pprint,我会得到:

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

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[0].movie__count现在我知道这不是完全想要的,所以你可以为注释添加一个名字:

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 你可以在这里查看文档: 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). 此外,它没有显示任何内容,因为django在模板上静默失败(因此设计师不会破坏整个页面)。 If you check the attributes, their names are movie__title and movie__count so you would have to change the template attributes to: 如果检查属性,则其名称为movie__titlemovie__count因此您必须将模板属性更改为:

{{ movie.movie__title }}: {{ movie.movie__count }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM