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
Model.objects.with_custom_ranking().order_by('custom')
Take note, only use this if the list you want to sort is small.
Written by Nam Ngo
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#