Python 在 Django 模板中访问查询集对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14321515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:04:37  来源:igfitidea点击:

Accessing query set object in django template

pythondjangodjango-templates

提问by sandeep

I have two models, named as Humanand 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.

我有两个模型,分别命名为HumanAnimal。Human 的主键是 Animal 模型中的外键。两者各有 3 列。人体模型有 c、e、r 列。动物模型有 l、i、p 列。我正在对 Human 模型运行 django 查询,就像这样。

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

resultis an queryset object. This object is sent from my view file to a django template page. Inside template page I am looping through resultand displaying the column values.

result是一个查询集对象。这个对象从我的视图文件发送到 django 模板页面。在模板页面内,我正在循环result并显示列值。

Now what i want to do is, I want to also fetch value of pcolumn(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.

现在我想要做的是,我还想p在同一循环中,在该 django 模板中获取列的值(存在于动物模型中)。我们如何在 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.

但我想在模板页面中做到这一点。

采纳答案by Aamir Adnan

{% for record in result %}
    {{record.c}}, {{record.e}}, 
    {% for animal in record.animal_set|slice:":1" %}
        {{animal.p}}
    {% endfor %}
{% endfor %}

回答by Jordan Jambazov

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. Second, in the example Python code you have presented, IndexErrors are not caught. 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:

首先,我想提一下您的数据库架构似乎有问题。如果“c”、“e”、“r”等是列的真实名称 - 考虑重命名它们。其次,在您提供的示例 Python 代码中,未捕获 IndexErrors。如果要获取第一个与 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.

给出的变量名称不同,但在您的情况下,最好重新考虑代码。