How to specify the order of values ​​in a drop-down list in Django ModelForm?

OK, here is the question.

class UserForm(forms.ModelForm):   

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

The models.pyclass Useris defined as follows:

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

Both teamand related_projectsare displayed as a drop-down list. Values ​​are all existing teams in the system and all existing projects in the system. Everything is fine, but they are only ordered by primary key, and I would like them to be ordered in alphabetical order. Where should I specify the order for the values ​​in the drop down list?

+5
source share
1 answer

team, queryset. , team, , 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

+13

All Articles