2016-10-25 76 views
0

我有一個表格,其中ModelMultipleChoiceField已被覆蓋以指定label_from_instance。按標籤排序選擇的最佳方式是什麼?在Django 1.8中使用ModelMultipleChoiceField排序label_from_instance

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

我知道我可以order_by,我通過在查詢集。雖然該作品排序的查詢集,它不會由label_from_instance進行排序。

回答

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) 
相關問題