【发布时间】: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