views:

47

answers:

2

I've got three models that show some sort of activity on a website I'm making. Song, Vote and Comment. They all share a common column when which shows when a record was created.

I want to show a list of activity based on all three models. In short I want to munge them together, sort by when, and scrape off the first 10 records.

How I do this is the question. I know I could get 10 recods for each model, put them in a dictionary and sort by date (well, once I know how to sort by date in Python), but this seems fairly inefficient.

+3  A: 

That probably is the way to do it. It wouldn't be that inefficient in fact - sorting 30 items is reasonably quick, and Python has a very good built-in sort algorithm.

items = list(Song.objects.order_by('when')[:10])
items.extend(list(Vote.objects.order_by('when')[:10]))
items.extend(list(Comment.objects.order_by('when')[:10]))

items.sort(key=lambda x: x.when)

items = items[:10]
Daniel Roseman
It still has to pull 20 more full records from the db into django than a pure-db version would, but yeah, that's not as filthy (code wise) as I thought it might be. I'll give it a shot and let you know how I get on.
Oli
+3  A: 

While it might be too late to get into re-working your models, one possibility is to pull out the common functionality into a parent class. That way you could simply run your queries off of the parent model.

Adam