CBV DetailView中的Django分页主详细信息
我有以下型号:CBV DetailView中的Django分页主详细信息,django,pagination,master-detail,Django,Pagination,Master Detail,我有以下型号: 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[Bo
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()
方法访问给定作者的书籍,但这会从数据库中提取所有行
我想把书排成页码
我如何做到这一点
更新:根据,我需要子类化
ListView
而不是DetailView
,并重写get\u queryset()
以获取书籍。在DetailView中有什么方法可以做到这一点吗?我相应地对列表视图进行了子类化
URL路由:
url(r'^author/((?P<pk>\d+)/$', AuthorView.as_view(), name='author_detail'),
详细视图中没有处理分页的代码。您当然可以使用带有DetailView
,但Daniel建议使用ListView
对我来说似乎是一种更好的方法。您如何在模板文件中循环浏览书籍?对不起。我的模板中有一些错误代码,导致所有书籍都被退回…:(
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