2016-10-25 14 views
0

label_from_instanceを指定するようにオーバーライドされたModelMultipleChoiceFieldのフォームがあります。選択肢をラベルで並べ替える最も良い方法は何ですか?DjangoのModelMultipleChoiceFieldでlabel_from_instanceで並べ替え1.8

class MultipleAuthorChoiceField(forms.ModelMultipleChoiceField): 
    def label_from_instance(self, obj): 
     label = author_display(obj) 
     return super(MultipleAuthorChoiceField, self).label_from_instance(label) 

私は、クエリセットをソートするために動作しますが、label_from_instanceによってソートするつもりはない。私は私が渡すクエリセットをorder_byできることを理解しています。ここで

答えて

0

は私が思い付いたものです:

from operator import itemgetter 

class MultipleAuthorChoiceField(forms.ModelMultipleChoiceField): 
    def label_from_instance(self, obj): 
     label = author_display(obj) 
     return super(MultipleAuthorChoiceField, self).label_from_instance(label) 

    def _get_choices(self): 
     choices = super(MultipleAuthorChoiceField, self)._get_choices() 
     for choice in sorted(choices, key=itemgetter(1)): 
      yield choice 
    choices = property(_get_choices, forms.ModelMultipleChoiceField._set_choices) 
関連する問題