change sort order of modelchoicefield django
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
ModelChoiceField
takes a QuerySet as its first parameter, so you should be able to pass an ordered set:
forms.ModelChoiceField(Company.objects.order_by('-pk'), required=True)
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 %}
精彩评论