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

309
Views
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 answers
Answer question

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 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!