I'm building a news website. While I tried to get the list of relative news which have the same tags. The error said:
The QuerySet value for an exact lookup must be limited to one result using slicing.
I have two models News
and Tag
. Tag is a many-to-many foreign key of News
.
News model:
class News(models.Model):
tag = models.ManyToManyField(Tag, blank=True, verbose_name='tag')
Tag model:
class Tag(models.Model):
name = models.CharField(max_length=40)
View:
def newsDetailView(request, news_pk):
news = get_object_or_404(News, id=news_pk)
tags = news.tag.annotate(news_count=Count('news'))
relative_news = News.objects.filter(tag=tags)
return render(request, "news_detail.html", {
'news': news,
'tags': tags,
'relative_news': relative_news
})
所有评论(0)