I'm using Python 3 and trying to convert a QuerySet into human-readable text. I have a line like this:
top_post = Post.objects.filter(category='1')[:1]
That prints like this:
<QuerySet [<Post: Test Post 1>]>
What makes me scratch my head is a similar QuerySet successfully converts when displayed via a template:
latest = Post.objects.order_by('-published_date')[:5]
"Latest" uses a for...loop in the template:
{% for latest_posts in latest %}
<h1>{{ latest_posts }}</h1>
While "top_post" displays only a blank:
<h1>{{ top_post }}</h1>
Anyone see what's missing?
{{top_post}} is a query set (slicing a queryset also produces a queryset), so it should display that. When you loop over the queryset, as you do over latest, you display the objects inside.
{{top_post.0}} would give you the object top_post contains.
Alternatively you can use
top_post = Post.objects.filter(category='1').first()
to get the object directly.
You should implement the __str__ method in the Post model where you define what to print.
Moreover you should .get instead of .filter if you expect one object to be returned.
Convert it into list
def
return(Post.objects.filter(category='1').first)