Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading