Things that fascinate me

Ordering arbitrary models by publishing date

So you have a bunch of blog entries and photos and links and such that you want to show in order. There’s at least two problems here:

  • Ordering a list of different objects on an unknown field.
  • Displaying these objects correctly in the templates.

For the last part of the problem, here’s a snippet I just posted ondjangosnippets.

from django import template

def display_excerpt(object, template_suffix='excerpt'):
    excerpt = object._meta.app_label + "/" + object._meta.module_name + "_" + template_suffix + ".html"
    try:
        t = template.loader.select_template([excerpt, 'display_excerpt.html'])
    except template.TemplateDoesNotExist:
        return str(object)
    c = template.Context({"object": object})
    return t.render(c)
register = template.Library()
register.simple_tag(display_excerpt)

This is all fine and well, but getting that list of objects sorted by date is a whole other matter.

For this site, I’m currently using this script.

def order_all_objects(model_list):
    """
    Takes a list of models and sorts items according to pub_date.
    """
    super_query = []
    for model in model_list:
        super_query += [item for item in model.all()]
    super_query.sort(key=lambda obj: obj.pub_date, reverse=True)
    return super_query

There are a few problems with this approach.

  • The name of the manager must be passed along with the model. In my case, I need to show Photos.objects.all() but Entries.live.all().
  • All the models need to have a pub_date field. If it’s named something else, I need to change the script. Worse, if each model has a differently named publishing date field, that will bring some more headaches.

I’m starting to formulate a different approach. A model dedicated to maintaining a running list of published content and times. Looping through that would be easy.

I think there’s a project there. To the DjangoMobile!