Error object is not iterable (Django)
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 the debugger refers to my template, to 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.
In the course of Googling, I realized that there is a difference between News.objects.filter(pk=q)
and News.objects.get(pk=q)
, but I do not understand what.
I would be very grateful if you could tell me what is the difference between them and how to start a code with News.objects.get(pk=q)
.
1 answers
When you write a query to the database via SomeModel.objects.filter()
, an object of type queryset
is created with a list of objects that can be traversed in the {% for %}
loop.
If queryset
returns a list of a single object, it will still be queryset
, so the loop worked for you.
When you write SomeModel.objects.get()
, you refer directly to the object, so you can not go through it in a loop, just if the object is not in the database, Django will return an exception, c filter()
there will be no exception.
Read in the documentation Django about database queries to better understand the intricacies of ORM work.