2017-03-07 53 views
0

我有以下型號:Django的分頁主詳細CBV中的DetailView

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

有一個在'DetailView'沒有代碼來處理分頁。你當然可以使用[分頁工具](https://docs.djangoproject.com/en/1.10/topics/pagination/)和'DetailView',但Daniel的建議使用'ListView'聽起來像是一個更好的方法。 – Alasdair

+0

你如何循環瀏覽模板文件中的書籍? – tdsymonds

+0

對不起。我的模板中有一些錯誤的代碼導致所有書籍被返回...... :( – masroore

回答

0

我已經相應地劃分了ListView

URL路徑:

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