Home > Enterprise >  How to filter books, so you get the authors books and not every book available, when you use ListVie
How to filter books, so you get the authors books and not every book available, when you use ListVie

Time:09-21

Authors books should only be displayed when tapping the authors name in the ListView.

models.py

from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
from django.utils.text import slugify

class Author(models.Model):´
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    slug = models.SlugField(unique=True, blank=False, null=False)


class Book(models.Model):

    author = models.ForeignKey(Author, on_delete=models.CASCADE, null=False, blank=False)
    title = models.CharField(max_length=200)
    price = models.FloatField()
    image = models.ImageField(null=True, blank=True)

views.py

from app.models import Book, Author
from django.shortcuts import render, redirect
from django.contrib.auth.models import User, Group
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView

class HomeView(ListView):
    model = Author
    ordering = ['-id']
    template_name = 'app/home.html'


class AuthorView(DetailView):
    model = Author
    template_name = 'app/author.html'
    

    def get_context_data(self, *args, **kwargs):
        # author_pk = self.kwargs.get('pk', None)

        # Tried this logic, but it makes no sense after I looked at it more close
        books = Book.objects.all()
        if books.author is Author.pk:
            books_filtered = books.objects.all()

        

        context = super(AuthorView, self).get_context_data(*args, **kwargs)

        context['books'] = books_filtered
        return context

Now when all authors are displayed on the home page with ListView, when someone clicks on an author they should see only the books the author has made with the DetailView

This link I tried but it will only display all the books

CodePudding user response:

You can use self.object to filter the books:

def get_context_data(self, *args, **kwargs):
    books = Book.objects.filter(author=self.object)
    ...

CodePudding user response:

You don't need to pass this to the template. In the template, you can work with:

{% for book in object.book_set.all %}
    {{book.title }}
{% endfor %}

here object is the Author for which we retrieve the books.

  • Related