change sort order of modelchoicefield django

Viewed 3425

how can I change the order of the values in the ModelChoiceField billing_company?

models.py

class Company(models.Model):
    name = models.CharField(max_length=30, unique=True)

forms.py

billing_company = forms.ModelChoiceField(Company.objects, required=True)

Thanks for your help. Tom

2 Answers

If you want to sort it in the template, you can manually render the form and iterate over the options and sort them using the dictsort templatetag (or any other templatetag that sorts according to what you like), e.g.

{% for value, option in form.fields.billing_company.choices|dictsort:1 %}
    <option value="{{ value }}">{{ option }}</option>
{% endfor %}
Related