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.

--

--

--

Software developer for over 20 years. Python programmer since 2015, using Django since 2017. Let me help you avoid the headache's I've endured.

Love podcasts or audiobooks? Learn on the go with our new app.

what i have been waiting for has come !

EVM: 1 VM Walkthrough

Meet the Scratcher: Zoe K.

How do reference latest Amazon Linux IDs using AWS Systems Manger Parameter Store?

How do reference latest Amazon Linux IDs using AWS Systems Manger Parameter Store?

Everything, everything is an object!

Google Cloud Architect Exam Study Materials — Updates for 2019 Re-certification

Version Control Systems Suck For Hackathons: Here’s Why

Reduce Cost and Increase Productivity with Value Added IT Services from buzinessware — {link} -

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Dennis Bottaro

Dennis Bottaro

Software developer for over 20 years. Python programmer since 2015, using Django since 2017. Let me help you avoid the headache's I've endured.

More from Medium

Django Framework

Django with Supervisor

Use Python Scripts to Insert CSV Data into Django Databases

Build a Django Application To Perform CRUD Operations