Accessing query set object in django template


Question

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
19
1/14/2013 3:44:52 PM

Accepted Answer

{% for record in result %}
    {{record.c}}, {{record.e}}, 
    {% for animal in record.animal_set|slice:":1" %}
        {{animal.p}}
    {% endfor %}
{% endfor %}
22
1/14/2013 3:52:48 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon