Answer a question

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
    })

Answers

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())
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐