JP van Oosten

Combining queries in Django

Jun 16, 2008

While implementing the code for this blog, I was wondering wether I should implement a “Links” application, where I would be able to add links I thought interesting. While investigating a method to combine the results for both this and the Post models, I found an interesting little feature in Python: operator.attrgetter.

So, if I have a list containing results from the two models (obtained through, for example, itertools.chain) I can sort them like this:

a.sort(key=operator.attrgetter('date')) 

It seems that this is more efficient on large datasets, than using

a.sort(lambda a,b: cmp(a.date, b.date))

but more interestingly, I think this is more in line with the way the STL works in C++.

import operator my new friend

(Oh, if you have two querysets for the same model, it is obviously more efficient to use q1 | q2.)