Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The QuerySet value for an exact lookup must be limited to one result using slicing-Django

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
    })
like image 945
William Avatar asked May 20 '18 04:05

William


3 Answers

The problem you are facing is that you first take a filter queryset (a collection of objects from your database) for example: Book.objects.filter(subject='fiction') ) and then you are trying to use that filter as a parameter (like subject = 'fiction' in the previous one ) to obtain another filter queryset.

Instead you have to use an object using 'get' instead of 'filter' that is the previous example would become

book = Book.objects.get(subject='fiction')

and then use that object as parameter for next filter.

example: Book_shelf = BookShelf.objects.filter(book = book)
like image 125
Sangeeth Joseph Avatar answered Sep 29 '22 03:09

Sangeeth Joseph


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())
like image 26
Lemayzeur Avatar answered Nov 16 '22 00:11

Lemayzeur


Generally this error occurs when we use model queryset at the place of django models object. In the given question you have done the same. "Objects.filter" returns the model query set there can be single or multiple django model objects, but "objects.get" returns single django model object. Or we can use .last() and .first() with "objects.filter".

like image 12
Shridhar Dhanopia Avatar answered Nov 16 '22 01:11

Shridhar Dhanopia