I'm loading a page in Django that summarizes information from a bunch of database objects. This is taking forever to load, and when I step through the view code the database processing is quick, it's just the render_to_response call that is taking forever.
The context that is being passed to the template has a bunch of database objects in it, so that certain parts of these objects may be displayed. Is there any overhead to that? An alternative approach would be to extract specific strings from the objects, and only add these strings to the context. I don't know enough about the template system to know if this would have any effect on the length of time it takes to render the template. I could see it having a big impact, or absolutely no impact at all, or anywhere in between.
As a follow-up, the actual cause of the slow performance of our site was due to some jQueryUI scripts we were linking to google for. When I downloaded them and installed them lo开发者_运维技巧cally, the page that took more than a minute to load before, now takes 3 seconds. The Django Toolbar helped to diagnose this problem, as I could see the SQL queries weren't the bottleneck.
What you have in the view is not "database processing code", it's "QuerySet generation code". And yes, that is fast. But when it comes time to actually hit the database and retrieve the rows, it takes time. Turn on logging in your database and figure out which queries are taking too long, and which you can do without.
Django's rendering engine is pretty quick. I would have thought that since the process of getting those values out of the objects has to be done at some point, it should be done in the correct place (the template).
Maybe your algorithm is inefficient?
To expand on Ignacio's point: just because the querysets are defined in the view, doesn't mean they are evaluated there. Most of the time, they aren't evaluated until they are accessed or iterated: and that usually happens in the template. So it's there in the template that the database access is probably happening, and that's what's probably taking the time.
As always, I recommend the Django debug toolbar - that will show you exactly where the db access is happening.
精彩评论