问题
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-Django.
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
})
Any friend can help?Thank you so much!
回答1:
The following will work:
def newsDetailView(request, news_pk):
news = get_object_or_404(News, id=news_pk)
relative_news = News.objects.filter(tag__id__in=news.tag.all())
来源:https://stackoverflow.com/questions/50431810/the-queryset-value-for-an-exact-lookup-must-be-limited-to-one-result-using-slici