I’m using django comments frameworks. All the comments are posted by authenticated users. Near the comment, I’m showing some user profile info using {{ comment.user.get_profile }}
{# custom comment list templates #}
<dl id="comments">
{% for comment in comment_list %}
<dt id="c{{ comment.id }}">
{{ comment.submit_date }} - {{ comment.user.get_profile.display_name }}
</dt>
<dd>
<p>{{ comment.comment }}</p>
</dd>
{% endfor %}
</dl>
Problem is that django’s comment queries does not use select_related() and for 100 comments I get 101 hit on the database.
Is there a way to make django comments framework to select user profile for each comment in one go?
I tested rendering 100 comments for an object with the default
{% get_comment_list %}tag and django did 200 comment related queries to list the comments + user + profile because…Comment.__unicode__actually callsComment.userif auser_idexists. +1 queryget_profile+1 queryOuch!
I went from 203 queries in ~25ms to 3 in ~2ms.
Populate comment_list yourself
I would highly suggest building the
comment_listQuerySetyourself using the appropriateselect_related()calls. If it’s used often, create a utility function called from your other views.If you want the entire framework to behave this way… You’ll have to monkey patch.
It’s not something I would do lightly. There are other ways around this specific problem but you did ask "in one go".
Put this somewhere in your
INSTALLED_APPSmodels.pyfiles. I actually have amonkey_patchapp for modifyingdjango.contrib.auth.models.User.usernamelengths and such (which is a last resort unlike here).Gotchas with profiles and select_related()
Note that your
UserProfileclass needs aOneToOneFieldtoUserwith arelated_nameequal to what you pass toselect_related(). In my example it’sprofileand you need django 1.2+. I recall stumbling on that before.