[Django]-Accessing query set object in django template


{% for record in result %}
    {{record.c}}, {{record.e}}, 
    {% for animal in record.animal_set|slice:":1" %}
    {% 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. 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):
    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.

Leave a comment