Changing to a new generic template 01.19.2007

Previously, I’ve been using the generic date based archive_list template. However, I wanted to divide the list of entries on the main page into a singe “featured” most recent entry, and an abbreviated list of past entries.

There were two ways of doing so that immediately came to mind within the date based template:

  1. Using the slice filter to slice the queryset within the template on the fly. So feature would be latest[1:1] and the recent entries would be latest[2:10].

  2. Using a bunch of conditionals testing against forloop.first to properly segregate the most recent post from the other recent posts.

Both options presented problems for me.

Option #1 worked well, but had the negative side effect of hitting against the database twice per page view. Once when splitting to get the featured entry (SQLish: SELECT … LIMIT 1), and then another query to the database to get the remaining entries (SQLish: SELECT … OFFSET 2 LIMIT 10).

I didn’t like the idea that something that could easily be done in one query was being done in two.

Option #2 makes the template parser do some heavy logical lifting, something that I’m not too keen on for what is ostensibly a very simple front page.

My final solution?

I switched to using the simple.direct_to_template generic view, and assigned two variables to the template context:

  1. recent where recent = list(Entry.objects.all()[:10])

  2. feature where feature = recent.pop(0)

One important note is that in my model definition for Entry, I have it set so that all queries for Entry are ordered by default against date, descending.

Basically, I’m getting all Entries, with the LIMIT set to 10, and then explicitly converting the queryset to a list of objects. That is assigned to recent.

Next, I’m popping off the first element of recent and assigning it to feature. This has the result of removing the latest post off of the recent list, and into the feature object.

With this method, the database gets hit only once, and I’m not doing any template logic heavy lifting beyond a simple loop to go through the recent entries list.