Accessing query set object in django template

本小妞迷上赌 提交于 2019-12-22 01:34:16

问题


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')

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.

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.

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.


回答1:


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



回答2:


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:

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.



来源:https://stackoverflow.com/questions/14321515/accessing-query-set-object-in-django-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!