Last Updated: February 25, 2016
· geeknam

Django order_by custom order in Postgres

Add this to your custom Manager:

def with_custom_ranking(self):
    # this should return a list of ids in order you want to sort
    ids = get_custom_ranking()

    if ids:
        clauses = ' '.join([
            'WHEN "app_model"."field"=\'%s\' THEN %s' % (id, idx)
            for idx, id in enumerate(ids)
    ordering = 'CASE %s END' % clauses
    return self.extra(
        select={'custom': ordering}

# You can now sort the queryset in a custom order

Take note, only use this if the list you want to sort is small.