Categorized: Django

Display Children of One-To-Many or Many-To-Many Relationships in your Django Templates

For items you’ve defined in the parent model, such as this:

class Project(models.Model):
    tasks = models.ManyToManyField(Task, blank=True)

You use parent.children.all, like so:

{% for task in project.tasks.all %}
    <li>{{ task.title }}</li>
{% endfor %}

For items defined outside of the parent model with a foreign key pointing back to the parent model, such as this:

class Picture(models.Model):
    project = models.ForeignKey(Project)

You use parent.children_set.all, like so:

{% for picture in project.picture_set.all %}
    <img src="{{ picture.image }}" alt="{{ project.title }}">
{% endfor %}

Sources

Comments

No name → February 5th, 2009 at 3:47 pm

What about the controller. You have the MV but no C. What about the missing piece.

Trey → February 5th, 2009 at 3:55 pm

This is Django, there is no MVC–it’s MTV. :)

MikkaH → September 26th, 2009 at 6:01 pm

Very helpfull tonight, Indeed I spend hours figuring out such a simple thing. And I am not per say a beginner but a transfuge from php. We love this framework, but the documentation ’sucks’. Like I say, It’s like parents sending away their offsprings, with this recommandation: Go gather knowledge elsewhere, and come back when you are grown up, to live with us. After to night I can go back and read and understand the many to many Explanation in the Django project. Same experience not so long ago with the generic views !! Thanks Trey ‘Saved my evening’. MikkaH.

abdulaziz → December 17th, 2009 at 5:23 am

thanks it works perfectly

What do you think about that?

Elsewhere in the empire: Home, Blog, APOD