开发者

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 %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜