首页 > 解决方案 > Django MultipleObjectsReturned at /author/Ed Sheeran get() 返回了不止一首歌曲——它返回了 2

问题描述

我正在用 Django 编写一个歌曲查看网站然后突然遇到这个错误

MultipleObjectsReturned at /author/Ed Sheeran get() returned more than one Songs -- it returned 2!

我试图设置我的网站,以便当用户点击任何歌曲的作者姓名时,他们将被重定向到另一个页面,其中只有该作者的歌曲。但不幸的是,我的代码遇到了这个错误。

我的模型.py:

class Songs(models.Model):
    title = models.CharField(max_length = 100)
    lyrics = models.TextField()
    author = models.CharField(max_length = 100)
    track_image = models.CharField(max_length=2083)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('/', kwargs={'pk': self.pk})

我的意见.py:

def home(request):
    context = {
        'songs': Songs.objects.all()
    }
    return render(request, 'home.html', context)

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)

我的html:

{% block content %}
<h1 class="mb-3">Songs by {{ view.kwargs.author }}</h1>
{% for song in songs %}
<article class="media content-section">
  <div class="media-body">
    <div class="article-metadata">
      <a class="mr-2" href="{% url 'author-songs' song.author %}">{{ song.author }}</a>
    </div>
    <h2><a class="article-title" href="{% url 'song-detail' song.id %}">{{ song.title }}</a></h2>
    <p class="article-content">{{ song.lyrics }}</p>
  </div>
</article>
{% endfor %}
{% endblock content %}

标签: django

解决方案


错误正在弹出,因为Model.objects.get(**args)应该始终返回 1 个结果。如果找到超过 1 个结果,则会引发此错误。

在这段代码中:

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)

这是抛出错误的行

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.

您需要做的是get_queryset像这样更新方法:

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

推荐阅读