简体   繁体   English

在django模板中访问查询集对象

[英]Accessing query set object in django template

I have two models, named as Human and Animal . 我有两个模型,命名为HumanAnimal The primary key of Human is foreign key in the Animal model. Human的主键是Animal模型中的外键。 Both has 3 columns each. 两者各有3列。 Human model has c, e, r columns. 人体模型有c,e,r列。 Animal model has l, i, p columns. 动物模型有l,i,p列。 I am running a django query on Human model, like this. 我在人体模型上运行django查询,就像这样。

result = Human.objects.filter().order_by('r')

result is an queryset object. result是一个queryset对象。 This object is sent from my view file to a django template page. 此对象从我的视图文件发送到django模板页面。 Inside template page I am looping through result and displaying the column values. 在模板页面内部,我循环遍历result并显示列值。

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. 现在我想做的是,我想在同一个循环内,在django模板中获取p列的值(它存在于Animal模型中)。 How can we do it in the django template page. 我们怎么能在django模板页面中做到这一点。

In the python file I can do like this 在python文件中,我可以这样做

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

First of all, I'd like to mention that something seems wrong with your database schema. 首先,我想提一下你的数据库模式似乎有些问题。 If "c", "e", "r" and others are the real names of the columns - consider renaming them. 如果“c”,“e”,“r”等是列的真实名称 - 请考虑重命名它们。 Second, in the example Python code you have presented, IndexErrors are not caught. 其次,在您提供的示例Python代码中,未捕获IndexErrors。 If you want to get the first Animal related to the Human object, it would be good to create a getter method in the Human model: 如果你想得到第一个与Human对象相关的Animal,最好在Human模型中创建一个getter方法:

def get_first_animal(self):
  try:
    return self.animal_set[0]
  except IndexError:
    return None

If you need to show all animals from the template, you can try something like this: 如果您需要显示模板中的所有动物,您可以尝试这样的事情:

{% for animal in human.animal_set.all %}
{{ animal }}
{% endfor %}

The variable names given are different, but in your case it would be good to re-factor the code. 给出的变量名称是不同的,但在您的情况下,重新考虑代码是很好的。

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

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