Reputation: 365
Attempting to get the most recent object in a query set and I keep getting error
TypeError at / 'PostManager' object is not iterable
How do you do this without iterating?
class DashboardTemplateView(TemplateView):
template_name = "base.html"
context_object_name = 'name'
def get_context_data(self, *args, **kwargs):
context = super(DashboardTemplateView,self).get_context_data(*args, **kwargs)
context["title"] = "This is about us"
return context
class MyView(ContextMixin, TemplateResponseMixin, View):
def get(self, request, *args, **kwargs):
context = self.get_context_data(**kwargs)
# mission_statement = Content.objects.filter(Content.objects.title == 'test')
# context = {'mission_statement' : mission_statement,
# 'content_list' : Content.objects.all(),
# 'post_list' : Post.objects.all()}
# context = {'content_list' : Content.objects.all(), 'post_list' : Post.objects.all()}
home_list = list(Post.objects).order_by('-id')[0]
context = {'content_list' : Content.objects.all(), 'home_list' : home_list.objects.all()}
return self.render_to_response(context)
Upvotes: 1
Views: 751
Reputation: 9931
A small paranthesis error on line below
home_list = list(Post.objects).order_by('-id')[0]
Change this to
home_list = list(Post.objects.all().order_by('-id'))[0]
An alternative one
home_list = Post.objects.all().order_by('-id').first()
Also calling objects method on home_list is not needed. Below would also work fine
context = {'content_list' : Content.objects.all(), 'home_list' : home_list}
Upvotes: 1
Reputation: 501
This line is wrong:
home_list = list(Post.objects).order_by('-id')[0]
Post.objects is the PostManager : it is not a iterable, you cannot list() it.
I guess what you are after is this:
home_list = Post.objects.all().order_by('-id').first()
The difference between first() and [0] is that first() won't throw IndexError if no result in query set, it will return None.
Upvotes: 2