在Django模板中访问查询集对象 [英] Accessing query set object in django template
问题描述
我有两个模型,分别是 Human
和 Animal
。人的主键是动物模型中的外键。两者都有3列。人体模型具有c,e,r列。动物模型具有l,i,p列。我正在像这样的人类模型上运行一个Django查询。
I have two models, named as Human
and Animal
. The primary key of Human is foreign key in the Animal model. Both has 3 columns each. Human model has c, e, r columns. Animal model has l, i, p columns. I am running a django query on Human model, like this.
result = Human.objects.filter().order_by('r')
结果
是一个查询集对象。该对象从我的视图文件发送到django模板页面。在模板页面内部,我遍历 result
并显示列值。
result
is an queryset object. This object is sent from my view file to a django template page. Inside template page I am looping through result
and displaying the column values.
现在我要做的是,我还想在同一django模板内的同一循环内获取 p
列(在Animal模型中存在)的值。
Now what i want to do is, I want to also fetch value of p
column(which is present in the Animal model) inside the same loop, inside that django template. How can we do it in the django template page.
在python文件中,我可以这样做
In the python file I can do like this
for i in result:
print i.animal_set.values()[0]['p']
但我想在模板页面中完成。
But I want to do it in the template page.
推荐答案
{% for record in result %}
{{record.c}}, {{record.e}},
{% for animal in record.animal_set|slice:":1" %}
{{animal.p}}
{% endfor %}
{% endfor %}
这篇关于在Django模板中访问查询集对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!