Danny
Danny

Reputation: 510

How to access "other side" of ManyToMany relationships in Django/Wagtail?

I think I'm lacking the right search term for what I'm looking for here.

I've got a model for BookPage that accepts multiple authors in a ParentalManyToMany relationship in Wagtail. I'm able to access each of the authors in a template using this code:

            {% with author=page.author.all %}
                {% if author %}
                    {% for aut in author %}
                    <div>
                        {{ aut }}
                    </div>
                    {% endfor %}
                {% endif %}
            {% endwith %}

This prints each author associated with a book.

How do I do the reverse, and get all the books written by a particular author, though? I can't seem to find anything about this in the Wagtail docs.

Upvotes: 1

Views: 384

Answers (1)

gasman
gasman

Reputation: 25317

This is covered by the Django documentation: https://docs.djangoproject.com/en/stable/topics/db/queries/#related-objects

When you define a relation such as a ParentalManyToManyField, Django will set up a property on the target model allowing you to query the relation in reverse - by default, this property is named after the other model with _set appended, so bookpage_set in this case:

{% for book in author.bookpage_set.all %}

You can specify a different name by providing related_name when setting up the ParentalManyToManyField:

authors = ParentalManyToManyField(Book, blank=True, related_name='books')  # - allows you to write author.books.all

Upvotes: 2

Related Questions