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 %}
Comments
What about the controller. You have the MV but no C. What about the missing piece.
This is Django, there is no MVC–it’s MTV. :)
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.
thanks it works perfectly
I had a few hard days trying to figure this out, when I finally ran into your article. Thank you so much! This is probably very basic, but if you can’t find documentations about it something simple soon gets pretty hard! I did a little talking and linking about and on this on my blog. Thanks a lot!
Cool. Like others, this stumped me.
Instead of .all, how does a .filter work? I can’t get that going, e.g.
{% for task in project.tasks.filter(status__eq=”Active”) %}
or something like that.
@rms Are you looking for template filters?
docs.djangoproject.com/en/dev/ref/templates/builtins/#filter
What do you think about that?