Django Models Parent Child Template Rendering
Just a quick little tip.
It took me quite a bit to time to stumble across this, as the Django documentation does not mention it.
If you have a ‘related_name’ set for a ForeignKey field on a model, USE that related_name as the MODELCHILD_SET name when trying to access related objects.
Working Example
Based on the example Polls app in the Writing your first Django app Documentation.
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
If you have in your models, the Choice model in your models.py file.
from django.db import modelsclass Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')class Choice(models.Model):
question = models.ForeignKey(Question,related_name='choices', on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
You will need to use that related_name in place of the modelname_set in the template to access the child objects.
Thus, your template would need to look like this otherwise you won’t get any objects from the ForeignKey relation.
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choices.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
I sure hope this helps someone scratching their head and endlessly checking their model names.
Originally published at http://www.dennisbottaro.com on February 11, 2020.