如何在Django ModelForm中的下拉列表中指定值的顺序? [英] How do I specify an order of values in drop-down list in a Django ModelForm?

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

问题描述

确定,这里是问题。

class UserForm(forms.ModelForm):   

    class Meta:
        model = User
        fields = ('team',  'related_projects') 

models.py 中,用户类定义如下:

class User (models.Model):
    team = models.ForeignKey(Team, verbose_name = _('team'))
    related_projects = models.ManyToManyField(Project, blank = True)

code>和 related_projects 呈现为下拉框。价值观是系统中现有的所有团队,以及系统中现有的所有项目。没关系,但是它们只是按主键排序,我想按字母顺序看到它们。我应该在下拉列表中指定值的顺序?

Both team and related_projects are rendered as a dropdown-box. The values are all the existing teams in the system, and all the existing projects in the system. That's all right, but they're only ordered by primary key, and I would like to see them ordered alphabetically. Where should I specify ordering for values in a drop-down list?

推荐答案

您需要指定 team 字段,然后您应该可以使用其 queryset 参数覆盖顺序。在这里,我假定您要排序的团队中的属性是名称

You'd need to specify an override for the team field and then you should be able to override the order with its queryset argument. Here I'm assuming the property in Team you want to sort on is name.

class UserForm(forms.ModelForm):
    team = forms.ModelChoiceField(queryset=Team.objects.order_by('name'))

    class Meta:
        model = User
        fields = ('team',  'related_projects') 

您可以在这里阅读更多关于ModelChoiceField的信息: http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield

You can read more about ModelChoiceField here: http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield

这篇关于如何在Django ModelForm中的下拉列表中指定值的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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