Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1K
Views
Django: How to Convert QuerySet into String

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

{{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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

Convert it into list

def 
return(Post.objects.filter(category='1').first)
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!