Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

1K
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

Convert it into list

def 
return(Post.objects.filter(category='1').first)
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda