【问题标题】:How to filter books, so you get the authors books and not every book available, when you use ListView and DetailView (Django)如何过滤书籍,以便在使用 ListView 和 DetailView (Django) 时获得作者书籍而不是每本书
【发布时间】:2021-11-13 22:52:32
【问题描述】:

只有在 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我试过了,但它只会显示所有的书

【问题讨论】:

    标签: django listview filter one-to-many detailview


    【解决方案1】:

    您可以使用self.object 过滤书籍:

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

    【讨论】:

      【解决方案2】:

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

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

      这里的object 是我们检索书籍的Author

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-04-30
        • 2020-12-17
        • 2020-12-13
        • 2019-05-22
        • 1970-01-01
        • 1970-01-01
        • 2021-05-17
        • 2011-12-24
        相关资源
        最近更新 更多