如何过滤书籍,以便在使用 ListView 和 DetailView (Django) 时获得作者的书籍,而不是每本可用的书籍

How to filter books, so you get the authors books and not every book available, when you use ListView and DetailView (Django)

只有在 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

现在,当所有作者以 ListView 显示在主页上时,当有人点击某个作者时,他们应该只会看到该作者用 DetailView

制作的书籍

这个link我试过了但是它只会显示所有的书

您可以使用self.object筛选书籍:

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

您不需要将其传递给模板。在模板中,您可以使用:

{% for <strong>book in object.book_set.all</strong> %}
    {{book.title }}
{% endfor %}

此处 object 是我们检索图书的 Author