Answer the question
In order to leave comments, you need to log in
How can you refactor a view?
There are two simple models:
models.py
class Author(models.Model):
name = models.CharField(max_length=255)
author_slug = models.SlugField(unique=True)
class Song(models.Model):
name = models.CharField(max_length=255)
song_slug = models.SlugField(unique=True)
song_author = models.ForeignKey(Author)
class SongListView(ListView):
model = Song
context_object_name = 'songs_list'
template_name = 'songs_list.html'
def get_queryset(self):
queryset = super(SongListView, self).get_queryset()
paginator = Paginator(queryset, 10)
page = self.request.GET.get('page')
try:
queryset = paginator.page(page)
except PageNotAnInteger:
queryset = paginator.page(1)
except EmptyPage:
queryset = paginator.page(paginator.num_pages)
return queryset
class AuthorSongListView(SongListView):
def get_queryset(self):
queryset = super(SongListView, self).get_queryset()
author = Author.objects.get(author_slug=self.kwargs.get('author_slug'))
paginator = Paginator(queryset.filter(song_author=author), 10)
page = self.request.GET.get('page')
try:
queryset = paginator.page(page)
except PageNotAnInteger:
queryset = paginator.page(1)
except EmptyPage:
queryset = paginator.page(paginator.num_pages)
return queryset
Answer the question
In order to leave comments, you need to log in
I would advise the paginator logic to use native for ListView.
class SongListView(ListView):
model = Song
context_object_name = 'songs_list'
template_name = 'songs_list.html'
paginate_by = 10
class AuthorSongListView(SongListView):
def get_queryset(self):
queryset = super(SongListView, self).get_queryset()
author = Author.objects.get(author_slug=self.kwargs.get('author_slug'))
return queryset.filter(song_author=author)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question