使用Django 1.8中的ModelMultipleChoiceField对label_from_instance进行排序

时间:2016-10-25 16:46:32

标签: python django django-forms

我有一个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我传入的查询集。虽然这可以对查询集进行排序,但它不会按D3D11CalcSubresource(level, 0, mipLevels); 排序。

1 个答案:

答案 0 :(得分: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)