0

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

2
  • 2
    Probably you may be trying to iterate BlogPost object in the detail view. Commented Apr 2, 2020 at 13:47
  • Well, get returns a single instance, filter returns a queryset which is an iterable over instances. Commented Apr 2, 2020 at 13:48

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You for helping
0

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.

Comments

0

just don't iterate in the template('don't use loops instead pass query.name or whatever is inside your modal ')

  1. first check whether the problem is really in 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.