Created
February 25, 2020 22:16
-
-
Save yoandresaav/bbf7a4c2a648b42c49c96a8a1aa2d43b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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