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

311
Visualizações
Print foreign key value in template without doing a query

I have a query that I do in my view to get a bunch of team stat objects...

    team_stats = NCAABTeamStats.objects.filter(
            name__name__in=teams_playing).order_by(sort)

One of the fields 'name' is a foreign key. I pass team_stats to my template to display the data in a chart via a 'for loop'.

    {% for team in team_stats %}
       <tr>
          <td>
              {{ team.name }}
          </td>
       </tr>
    {% endfor %}

So in my template, for every object in team_stats it is doing a query when it prints {{ team.name }} and it really slows things down, especially when there are 50-100 teams.

My question is, is there a way to print 'team.name' without it doing a query every time?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

if it is a foreignkey you can do something like this

team_stats=NCAABTeamStats.objects.select_related('name').filter(name__name__in=teams_playing).order_by(sort)

you can learn more on select_related here

if it is a manytomany field you can do something like this

team_stats=NCAABTeamStats.objects.prefetch_related('name').filter(name__name__in=teams_playing).order_by(sort)

you can learn more on prefetch_related Here

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