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 way back, 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: {% for other in loan.book.loans.all %} goes forward, then back to every loan of the same book. A misspelled name shows nothing, with no error, so when a list comes out empty, check the names first.

challenge icon

Challenge

Easy
  • Give Book.author the way back name books.
  • 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 open a book's page.

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