Reputation: 45
get() method is not working in Django,
I have a model BlogPost, when I try to fetch data from that model using get() method it shows
Error : 'BlogPost' object is not iterable
def blog_post_detail(request, slug):
query = BlogPost.objects.get(slug=slug)
template_name = 'blog/post.html'
context = {'query': query}
return render(request, template_name, context)
But the same thing works using filter() method
def blog_post_detail(request, slug):
query = BlogPost.objects.filter(slug=slug)
template_name = 'blog/post.html'
context = {'query': query,}
return render(request, template_name, context)
Note: I have only one post in BlogPost
Upvotes: 0
Views: 1762
Reputation: 3
just don't iterate in the template('don't use loops instead pass query.name or whatever is inside your modal ')
get()
.method :
def blog_post_detail(request, slug):
query = BlogPost.objects.get(slug=slug)
print(query)
return HttpResponse(query)
Before using this make sure you used
def __str__(self):
return self.name
in your model and import HttpResponse
if this returns Httpresponse or printed data then Don't use for loop in your template
Upvotes: 0
Reputation: 2909
Calling .get()
on a queryset will return a single instance of that model. There's a for loop in Your template iterating over the instance.
Upvotes: 3
Reputation: 1304
The error is not happening during the .get()
operation. It's being caused when you're passing the context
in the template. Pretty sure the code in your template is iterating over your context.query
and showing the BlogPost object.
Upvotes: 0