Reputation: 315
I'm new to Python / Django coming from a PHP background and had a question. I have the debug toolbar enabled and it appears as if when I reference variables in the template that I built in the view and pass to the template it is result in an SQL query. In other words, the template is making another query to the database instead of using the variable that was built in the view.
Here is one example of what I am talking about. With this being the case, a page that has many variables printed could have well over 100 queries which doesn't seem right. I am assuming that there is something fundamental that I am missing and have done some thorough research but can't seem to figure it out. Any help would be appreciated, thanks!
View:
def test(request):
weather = []
w = Weather_main.objects.filter(location_id=3)
w = w.select_related('location__name')
weather.append(w)
w = Weather_main.objects.filter(location_id=6)
w = w.select_related('location__name')
weather.append(w)
w = Weather_main.objects.filter(location_id=9)
w = w.select_related('location__name')
weather.append(w)
context = {'weather': weather,
'num_weather_locs': range(len(weather))}
return render(request, 'test.html', context)
Template:
{% load app_filters %}
<BODY>
{{ status }} <br><br>
{% if weather %}
{% for w in weather %}
{{ w.0.location.name }}<br>
{{ w.0.weather_date }}<br><br>
{% endfor %}
{% else %}
<p>Weather does not exist</p>
{% endif %}
</BODY>
Upvotes: 1
Views: 1117
Reputation: 474131
In order to join weather info for different locations, better use a single query with __in
:
def test(request):
weather = Weather_main.objects.filter(location_id__in=[3, 6, 9]).select_related('location__name')
context = {'weather': weather}
return render(request, 'test.html', context)
Then, in the template, iterate over the weather
queryset:
{% for w in weather %}
{{ w.location.name }}<br>
{{ w.weather_date }}<br><br>
{% endfor %}
Upvotes: 2