Menu
CoddyTech

Related Names

Part of the Models and the Admin section of Coddy's Django journey. Lesson 17 of 23.

A book's page could list the author's other books. That means going from the author back to their books: a ForeignKey works in both directions. With a Loan pointing to a book, loan.book goes forward, and Django adds a manager to Book for the reverse direction, named after the model plus _set: book.loan_set.all(). related_name gives it a better name:

book = models.ForeignKey(Book, on_delete=models.PROTECT, related_name="loans")

Now book.loans.all() returns that book's loans, book.loans.count() works as on Loan.objects, and loan_set no longer exists.

Templates follow relations with dots and call methods without parentheses: On a book's page, {% for loan in book.loans.all %} lists that book's loans. A misspelled name shows nothing, with no error, so when a list comes out empty, check the names first.

challenge icon

Challenge

Easy

List the author's other books on each book's page.

  1. In books/models.py, give Book.author the related name books, so author.books.all() returns every book by that author.
  2. In book_detail.html, above the Back link, add an <h2> like More by Frank Herbert and a <ul class="more"> listing every book by that author, each a link to its page.

Press Run and click Dune: under More by Frank Herbert you see Children of Dune and Dune.

Try it yourself

{% extends "books/base.html" %}

{% block title %}{{ book.title }}{% endblock %}

{% block content %}
<h1>{{ book.title }}</h1>
<p class="author">by {{ book.author }}</p>
<ul>
    <li>Published in {{ book.year }}</li>
    <li>Genre: {{ book.get_genre_display }}</li>
    <li>Price: {{ book.price }}</li>
</ul>
<p><a href="{% url 'books:home' %}">Back to the shelf</a></p>
{% endblock %}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Models and the Admin

Practice on your own: Django playground