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?
CodePudding user response:
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