Django template filter - sort by multiple keys
keys is already visible in compare, so you can even do the splitting
outside of compare and still use it inside of it.  And the duplication
of code for the else branch should be eliminated, by only doing the
comparison once (cmp should work I guess) and then negating the
result if necessary.  This means processing all the keys before
running the sorting into a useful data-structure.  You want to compare
in the order they are specified, so a list of tuples will do fine.

Then, by using cmp instead of normal comparisons three lines per
branch are eliminated.  Also, which is maybe more important, you don't
have to worry about the comparisons and what -1/1, which personally
takes me way to long all the time while reading comparison functions
like this.

The two branches are also unnecessary, since you can just negate the
result depending on the sort key (factor in the following code).

So I arrive at this, untested of course.

@register.filter
def sort_by_keys(value, keys):
    transformed = []
    for key in keys.split(','):
        factor = 1
        if key.startswith('-'):
            key = key.replace('-', '')
            factor = -1
        transformed.append((key, factor))

    def compare(item1, item2):
        for (key, factor) in transformed:
            result = factor * cmp(getattr(item1, key), getattr(item2, key))
            if result != 0:
                return result
        return 0

    return sorted(list(value), cmp=compare)


It looks like you can't use sort directly on the input value?
Otherwise I'd suggest to do that as well.

Apart from completely compiling the sort function beforehand (using
lambdas), this seems the most compact I think.