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

san*_*eep 19 python django django-templates

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

result = Human.objects.filter().order_by('r')
Run Code Online (Sandbox Code Playgroud)

result是一个queryset对象.此对象从我的视图文件发送到django模板页面.在模板页面内部,我循环result并显示列值.

现在我想做的是,我想p在同一个循环内,在django模板中获取列的值(它存在于Animal模型中).我们怎么能在django模板页面中做到这一点.

在python文件中,我可以这样做

for i in result:
    print i.animal_set.values()[0]['p']
Run Code Online (Sandbox Code Playgroud)

但我想在模板页面中这样做.

Aam*_*nan 22

{% for record in result %}
    {{record.c}}, {{record.e}}, 
    {% for animal in record.animal_set|slice:":1" %}
        {{animal.p}}
    {% endfor %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)


Jor*_*zov 5

首先,我想提一下您的数据库架构似乎有问题。如果“c”、“e”、“r”等是列的真实名称 - 考虑重命名它们。其次,在您提供的示例 Python 代码中,未捕获 IndexErrors。如果你想获得第一个与 Human 对象相关的 Animal,最好在 Human 模型中创建一个 getter 方法:

def get_first_animal(self):
  try:
    return self.animal_set[0]
  except IndexError:
    return None
Run Code Online (Sandbox Code Playgroud)

如果您需要显示模板中的所有动物,您可以尝试如下操作:

{% for animal in human.animal_set.all %}
{{ animal }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

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