Looks like a genre has a genre group associated with it, right? You could use select_related [1] method when selecting all genres, so, when Django executes the query, all the relation comes in only one query.
[1] https://docs.djangoproject.com/en/1.3/ref/models/querysets/#django.db.models.query.QuerySet.select_related That is all the improvement that I can see in your code, and I agree with Tom, but I don't consider using select_related as a premature optimization, I always use it. :) []'s On Mon, Oct 24, 2011 at 9:17 AM, Tom Evans <[email protected]> wrote: > On Mon, Oct 24, 2011 at 11:59 AM, Kurtis <[email protected]> wrote: > > Hey guys, > > > > I have some custom context in a view. I'm going to be replicating this > > context three times for different object relationships. I didn't > > count, but looking at django-debug-toolbar I'm thinking this block of > > code runs at around 10 queries. Times that by 3 and I'm going to be > > bogging my application down in no time. > > > > The code is here: http://dpaste.com/640165/ > > > > Thanks! > > > > Couple of suggestions: > > 1) Cache the data. You will need to work out a good (correct) key > based upon the kwargs. If the info will only be useful on this > request, but you need to access it multiple times within that request, > you can simply add it as an attribute on the request. Otherwise, stick > it in memcached, with a short TTL (and make sure you invalidate the > cache when the data behind it changes). > You could also cache individual components of this. The Genre and > GenreGroup information is distinct and unchanging from the item > specific components of it. > > 2) Get dirty into raw SQL and hand tune the queries you issue so that > you can optimize this function. It's possible that you could work this > out into one (complex) query. > > 3) "We should forget about small efficiencies, say about 97% of the > time: premature optimization is the root of all evil" Knuth knows what > he is talking about, if you haven't noticed a problem, just remember > that this code is a possible optimization win, and revisit when it > actually is slow. > > BTW, I only count 3 queries there… > > Cheers > > Tom > > -- > You received this message because you are subscribed to the Google Groups > "Django users" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group at > http://groups.google.com/group/django-users?hl=en. > > -- Flávia Missi @flaviamissi <http://twitter.com/flaviamissi> flaviamissi.com.br https://github.com/flaviamissi -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

