如何在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