Rewriting some piece of code using pure sql instead of pseudo
django query language (too slow for our purposes...)