Search code examples
djangodjango-modelsdetailview

Django: How to get a Object over a Object related with Foreign Keys


I'm doing a webapp with django. At the moment i'm a bit stuck with DetailViews and displaying data from different models in relation to Foreign Keys.

For excample i have the following models:
- Library
- Book (related to Library)
- Page (related to Book)

At the moment I have a DetailView with the model Book.
I managed to access the Book with "_set.all".
Now I also need to access the Page of that Book.

Models.py:

class Library(models.Model):
    name = models.CharField(max_length=50)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

class Book(models.Model):
    title = models.IntegerField()
    library = models.ForeignKey(Library, on_delete=models.CASCADE)

class Page(models.Model):
    content= models.CharField(max_length=50000)
    book = models.ForeignKey(Book, on_delete=models.CASCADE)

Views.py

class TableDetailView(User, LoginRequiredMixin, DetailView):
    model = Library
    template_name = 'library/table.html'
    context_object_name = 'library'

table.html

<ul>
    {% for book in library.book_set.all %}
        <li>{{ book.title }}</li>
    {% endfor %}
</ul>
<!-- Works until here -->
<ul>
    {% for page in library.book.page_set.all %}
        <li>{{ page.content }}</li>
    {% endfor %}
</ul>

How can i get the content of the page displayed on my view? Thanks for any help <3


Solution

  • library.book is not a proper relation. For the usecase you are trying to implement,

    <ul>
        {% for book in library.book_set.all %}
            <li>{{ book.title }}
                <ul>
                    {% for page in book.page_set.all %}
                        <li>{{ page.content }}</li>
                    {% endfor %}
                </ul>
            </li>
        {% endfor %}
    </ul>