29👍
✅
{% for record in result %}
{{record.c}}, {{record.e}},
{% for animal in record.animal_set|slice:":1" %}
{{animal.p}}
{% endfor %}
{% endfor %}
4👍
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.
- [Django]-What does request.user refer to in Django?
- [Django]-How to convert a list in to queryset django
- [Django]-How to get URL of current page, including parameters, in a template?
Source:stackexchange.com