DGDD
DGDD

Reputation: 1390

Django: Show reverse object relationship in templates

In the templates page, when I want to cycle through the variables of an object related by a foreign key, I use the set.all function.

For example:

{% for object2_info in object1.object2_set.all %}
   {[object2_info.something}}
{% endfor %}

What I don't get is how can I do this in reverse? You would think it would be something like this:

{% for object1_info in object2.object1_set.all %}
   {[object1_info.something}}
{% endfor %}

but, that's not the case.

Any help would be appreciated.

Upvotes: 1

Views: 1504

Answers (1)

sk1p
sk1p

Reputation: 6725

This depends on your model definitions. Let's assume you have the following many-to-many-relationship:

class Autor(models.Model):
    name = models.CharField(max_length=42)

class Entry(models.Model):
    title = models.CharField(max_length=21)
    authors = models.ManyToManyField(Author)

Here, we can access the entries like in your first example, assuming we pass as Author object to our template:

{% for entry in author.entry_set.all %}
    {{ entry.title }}
{% endfor %}

But there is no author_set on Entry, because we explicitly named it: authors.

{% for author in entry.authors.all %}
    {{ author.name }}
{% endfor %}

You can read more about this in the official documentation.

Upvotes: 1

Related Questions