Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

1K
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

0

Convert it into list

def 
return(Post.objects.filter(category='1').first)
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda