3👍
If profile.get_somestuff
is an expensive operation and you call it multiple times in the template, and yes, you should call that in the view once and pass the result to the template via context
.
def view(request):
...
stuff = request.user.profile.get_somestuff()
return render(request, 'page.html', {'stuff': stuff})
Alternatively, you can use {% with %}
tag to create a scope containing the value in its own context:
{% with stuff=user.profile.get_somestuff %}
...
{{ stuff.info }}
{{ stuff.other_info }}
... do some other things with stuff
{% endwith %}
Personally, I would go with the first option because, with the help of django.db.connection.queries
, it is relatively easier to monitor db queries you make in the view. Make sure you avoid sending template querysets, lazy expressions etc. as much as possible.
BTW, please note that DEBUG
must be set to True
for connection.queries
to work.
3👍
If stuff.info or stuff.other_info are foreign keys to other models then yes, each time you hit each of those for a new stuff obj you could be doing another select query for each one.
select_related might help you here. It’ll effectively join the relevant tables on the fk fields you specify in the sql query upfront. The sql query will be more complex than the queries you’re running now but far less numerous.