如何在 Django ModelForm 的下拉列表中指定值的顺序? [英] How do I specify an order of values in drop-down list in a Django ModelForm?
问题描述
好的,问题来了.
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ('team', 'related_projects')
在 models.py
中,User
类定义如下:
In models.py
the User
class is defined as follows:
class User (models.Model):
team = models.ForeignKey(Team, verbose_name = _('team'))
related_projects = models.ManyToManyField(Project, blank = True)
team
和 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
参数.这里我假设您要排序的 Team
中的属性是 name
.
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屋!