How to order choices based on their name instead of their index?
This is my first post on stackoverflow, I'm going to try to follow the basic rules but be gentle with me.
I have to make a few changes (which appeared superficial at first glance) to a django app. The client wants all the dropdown menus of the forms in the admin part of the site to be sorted alphabetically. The problem is that some of these choices are based on static lists defined in the models.py files like this one :
STATE=(
(1, 'Full'),
(2, 'Damaged'),
(3, 'Partially damaged')
)
I tried to reorder the list like that :
STATE=(
(2, 'Damaged'),
(1, 'Full'),
(3, 'Partially damaged')
)开发者_如何学JAVA
but it doesn't seem to make a difference (although I'm not really familiar with the way Python caches classes and views).
Reordering the indexes like that :
STATE=(
(1, 'Damaged'),
(2, 'Full'),
(3, 'Partially damaged')
)
works but would mean writing some huge and complicated SQL scripts to keep the old data consistent (since most of the lists are longer than this one and permutations would become more complex).
So my question is : Is there a way to sort these choices based on their name instead of the index ? Maybe in the definition of the models.IntegerField(..., choices=STATE)
?
Thank you all.
changing the choices attribute of the form field to the sorted choices should fix your problem.
forms.py
class YourAdminForm(forms.Form):
def __init__(self, *args, **kwargs):
super(YourAdminForm, self).__init__(*args, **kwargs)
sorted_choices = sorted(YourModel.STATE, key=lambda x: x[1])
self.fields['field'].choices = sorted_choices
and:
from django.contrib import admin
from models import Your
from forms import YourAdminForm
class YourAdmin(admin.ModelAdmin):
form = YourAdminForm
admin.site.register(Your, YourAdmin)
Slightly more concise notation:
sorted_state = sorted(STATE, key=lambda x: x[1])
精彩评论