开发者

Optimizing Django queries

I have a page where users can see the comments list for a specific product.

In the view I get the list with:

comments = product.comments.all().order_by('-timestamp')

and this piece in the template:

1   {% if comments %}
2       {% for comment in comments %}
3       <div class="comment">
4           <a href="/user/{{ product.author }}/">{{ comment.author }}</a>
5           <br>{{ comment.text }}
6       </div>
7       {% endfor %}
8   {% endif %}

Using django debug toolbar when I go to a product page I can see that Django performs many queries are many comments in the list. For example in a product page with a comments list of 10 comments, Django performs about 15 queries. If I submit a new comment, the queries count rises to 16.

If i try to remove {{ comment.author }} (line 4), the queries decrease to a fi开发者_运维问答xed number, if I submit new comments. How to optimize this?

NB: comment.author is a ForeignKey to a django.contrib.auth.models.User


I think this is a case for select_related?

https://docs.djangoproject.com/en/dev/ref/models/querysets/#select-related

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜