我有以下型号:
class Book(models.Model):
name = models.CharField()
authors = models.ManyToManyField('Author', blank=True, verbose_name=_('authors'))
class Author(models.Model):
name = models.CharField()
def my_books(self) -> List[Book]:
return Book.objects.filter(authors__exact=self.id).all()
我通过DetailView
显示作者和相关书籍:
class AuthorDetailView(generic.DetailView):
model = Author
在模板中,我通过author.my_books()
方法访问给定作者的书籍 - 但这会从数据库中提取所有行。
我想对图书行进行分页。
我如何实现这一目标?
更新:根据this answer,我需要继承ListView
而不是DetailView
,并覆盖get_queryset()
来获取图书。有没有办法在DetailView中做到这一点?
答案 0 :(得分:1)
我已相应地对ListView
进行了分类。
网址路径:
url(r'^author/((?P<pk>\d+)/$', AuthorView.as_view(), name='author_detail'),
CBV:
class AuthorView(generic.ListView):
model = Book
paginate_by = 2
def get_queryset(self):
pk = int(self.kwargs['pk'])
return Book.objects.filter(authors__id__exact=pk)
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
pk = int(self.kwargs['pk'])
author = get_object_or_404(Author, pk=pk)
context['author'] = author
return context