[Answered ]-Django MultipleObjectsReturned at /author/Ed Sheeran get() returned more than one Songs β€” it returned 2

1πŸ‘

βœ…

The error is popping up because Model.objects.get(**args) should always return 1 result. If it finds more than 1 result, it throws this error.

In this code:

class AuthorSongListView(ListView):
    model = Songs
    template_name = 'author_songs.html'
    context_object_name = 'songs'
    paginate_by = 2

    def get_queryset(self):
        author = get_object_or_404(Songs, author=self.kwargs.get('author'))
        return Songs.objects.filter(author=author)

This is the line that is throwing error

author = get_object_or_404(Songs, author=self.kwargs.get('author'))

# this is trying to fetch Songs for the given author like this
Songs.objects.get(author=self.kwargs.get('author'))
# Since there are multiple songs for the author, this is throwing error.

What you need to do is update the method get_queryset like this:

def get_queryset(self):
   return Songs.objects.filter(author=self.kwargs.get('author'))

Leave a comment