如何在Django ModelForm中的下拉列表中指定值的顺序?

编程入门 行业动态 更新时间:2024-10-25 17:16:52
本文介绍了如何在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的信息: docs.djangoproject/en/dev/ref/forms/fields/#modelchoicefield

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

更多推荐

如何在Django ModelForm中的下拉列表中指定值的顺序?

本文发布于:2023-11-27 20:57:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1639575.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中指   顺序   定值   如何在   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!