django - 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 %}
解决方案
错误正在弹出,因为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'))
推荐阅读
- python - 收到错误:ModuleNotFoundError: No module named
对于我通过 pip 安装的所有内容 - codenameone - 代号:设置文本光标/插入符号的颜色
- python - 过滤掉python pandas中两个百分位数之间的数据
- java - 如何在更改全屏/上方导航时使用导航组件 navhostfragment
- python - Django Channels NOT NULL 约束失败:chat_chatmessage.message
- r - 在 R 中阅读后,我的文本中有很多空格,如何消除它们?
- html - Elm-ui 中的表单
- dolphindb - 如何在 DolphinDB 数据库中导入没有列名行的 csv 文件
- java - 安卓单行吐司
- javascript - JSON 到 HTML 表比较和警报