1

I have the following models:

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()

I am displaying author and related books via DetailView:

class AuthorDetailView(generic.DetailView):
    model = Author

In the template, I am accessing books of a given author via author.my_books() method - but this pulls ALL ROWS from the database.

I want to paginate the book rows.

How do I achieve that?

Update: According to this answer, I need to subclass ListView rather than DetailView, and override get_queryset() to fetch the books. Is there any way to do that in DetailView?

Community
  • 1
  • 1
masroore
  • 9,668
  • 3
  • 23
  • 28
  • There is no code in the `DetailView` to handle pagination. You could certainly use the [pagination tools](https://docs.djangoproject.com/en/1.10/topics/pagination/) with `DetailView`, but Daniel's suggestion to use `ListView` sounds like a better approach to me. – Alasdair Mar 07 '17 at 16:57
  • How are you looping through the books in the template file? – tdsymonds Mar 07 '17 at 17:08
  • sorry. there was some erroneous code in my template which caused all books to be returned... :( – masroore Mar 07 '17 at 17:09

1 Answers1

1

I have subclassed ListView accordingly.

URL route:

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
masroore
  • 9,668
  • 3
  • 23
  • 28