Hello everyone, I encountered the error "object is not iterable" and do not understand how to solve it:

there is a code snippet views.py

def search(request): try: q = request.POST['clientSearch'] result = News.objects.get(pk=q) context={'result': result} except News.DoesNotExist: raise Http404("News does not exist") return render(request,'news/search.html', context) 

when executing the request, an error occurs and debugger refers to my template, on the 1st line:

 {% for result in result %} {{ result.title }} {% endfor %} 

The most interesting thing is that with result = News.objects.filter(pk=q) everything works.
During Google, I realized that there is a News.objects.filter(pk=q) between News.objects.filter(pk=q) and News.objects.get(pk=q) , but I don’t understand what.
I would be very grateful if you tell me what the difference is between them and how to get the code with News.objects.get(pk=q) .

    1 answer 1

    When you write a database query via SomeModel.objects.filter() , an object of the type queryset is created with a list of objects that can be bypassed in the {% for %} loop.
    If the queryset returns a list of one object, it will still be a queryset , so the loop worked for you.
    When you write SomeModel.objects.get() , you refer directly to the object, respectively, it is impossible to go through it in a loop, just if the object is not in the database, Django will return an exception, c filter() will not be an exception.
    Read the Django documentation on database queries to better understand the fine points of ORM.

    • Thanks, it helped. - Konstantin