Using Django for csman has mostly been a positive experience, although there have been a few wrinkles along the way. I just ran into another one today, which is quite frustrating — one of my pages takes about ten seconds to render, and nobody wants to wait ten seconds! Fortunately it’s for the teachers and not the students; if it were for the students, there would be no end of whining!
This page includes a LOT of database queries, almost to the point where I should be embarrassed, except for the fact that I hacked this thing together as quickly as possible, so actually I’m proud that it has as many features as it has. But for 130 students and around 15 assignments, the server-side code issues around 2000 queries, and you don’t need to be a genius to know that this just won’t be very fast.
But surprisingly enough, only about half the time is spent in database land; the rest of the time is spent rendering the Django template. I was quite surprised by this! I thought it would be much faster than that, but evidently not. There are three nested loops in the template, iterating over a large amount of data, so in retrospect it’s no surprise, but an hour ago I was sure that I needed to optimize the database interactions, not the template rendering. Now I see that the database code is only half of the problem.
All I did to find this was to add a couple of print statements around my view code to see how much time was actually spent in the database queries. I’m glad I did; I would have been completely befuddled, otherwise. It just goes to prove that old bit of software engineering wisdom, that if you try to optimize a system before you’ve actually profiled it, you probably won’t fix the real bottleneck.
I think I can fix this issue by creating a custom template-tag that will move some of the rendering into Python code, instead of being run in the template engine. The more I can incorporate into Python, the better off I’ll probably be. This may also help with the database side of things, because if I have clever template tags, then I can do less preparation with the data, and therefore fetch larger amounts of data from the back-end in one shot.