Skip to content

Instantly share code, notes, and snippets.

@yoandresaav
Created February 25, 2020 22:16
Show Gist options
  • Save yoandresaav/bbf7a4c2a648b42c49c96a8a1aa2d43b to your computer and use it in GitHub Desktop.
Save yoandresaav/bbf7a4c2a648b42c49c96a8a1aa2d43b to your computer and use it in GitHub Desktop.
I don't think Django queryset has a mechanism to order by a list of field value.
Option 1:
Order in Python. Keep it mind it will return a list, not a queryset anymore (inspired from this answer) and that you end up using magic strings (what if the user uses Entrées instead of Starters?):
sections = Section.objects.all()
order = ['Starters', 'Salads', 'Desserts']
order = {key: i for i, key in enumerate(order)}
ordered_sections = sorted(sections, key=lambda section: order.get(section.name, 0))
https://stackoverflow.com/questions/42682652/django-query-sort-by-value-of-string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment