如何在ModelForm中对ChoiceField进行排序? [英] How to sort a ChoiceField in a ModelForm?

查看:77
本文介绍了如何在ModelForm中对ChoiceField进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含用户字段的模型。

I have a model that contains a user field.

usr = models.ForeignKey(User, related_name='+', limit_choices_to={'is_active': True})

我有一个 ModelForm (如下所示)允许设置 usr :一切正常。但是,用户列表是以随机顺序显示的。

I have a ModelForm (shown below) that allows the usr to be set: this all works fine. However, the list of users is presented in a random order.

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['usr', ]

如何在下拉列表中对活动用户列表进行排序?

How can I sort the list of active users in the drop down?

推荐答案

一个选项是设置 订购 。在您的表单中,模型选择字段应使用相同的顺序。

One option is to set the ordering for your model. In your form, the model choice field should use the same ordering.

class MyModel(models.Model):
    ...

    class Meta:
        ordering = ['username']

如果要在模型表单中进行其他排序,则可以使用 ModelChoiceField 并订购查询集。

If you want a different ordering in your model form, then you can use a ModelChoiceField and order the queryset.

class MyModelForm(forms.ModelForm):
    usr = forms.ModelChoiceField(Usr.objects.order_by('username'))
    class Meta:
        model = MyModel
        fields = ['usr', ]

这样的缺点是您会丢失模型字段中的信息(例如 help_text ),除非您以表格形式复制它。

The disadvantage of this is you lose information from the model field (e.g. help_text) unless you duplicate it in the form.

为防止重复,您可以替换<$中的查询集c $ c> __ init __ 方法。

To prevent duplication, you can replace the queryset in the __init__ method.

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['usr', ]

    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        self.fields['usr'].queryset = self.fields['usr'].queryset.order_by('username')

这篇关于如何在ModelForm中对ChoiceField进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆