I
I
Igor Malyshev2015-12-20 22:01:37
Django
Igor Malyshev, 2015-12-20 22:01:37

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)

and two views:
views.py
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

The first view lists absolutely all songs, 10 per page. The second outputs 10 songs per page, but owned by a specific artist. Is it possible to somehow improve the second view, otherwise it turns out that I am repeating myself in writing pagination?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Kitaev, 2015-12-21
@Domuk

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 question

Ask a Question

731 491 924 answers to any question