在 Django 模型选择字段中显示月份名称而不是月份编号(从数据库中获取)

Show month name instead of month number (fetched from db) in django model choice field

acct_per_num table SAPAdjustment 中的列包含月份数。以下代码给出了一个下拉菜单,其中包含 acct_per_num 列中的唯一月份编号 (1,2,3) in table SAPAdjustment 但我想要月份名称(一月、二月、三月)而不是月份编号(1、2、3)。

forms.py

class SAPReconForm(forms.Form):
    month = forms.ModelChoiceField(queryset=SAPAdjustment.objects.values_list('acct_per_num',flat=True).distinct(), empty_label=None)

models.py

class SAPAdjustment(models.Model):
    acct_per_num =  models.IntegerField( blank=True,null=True, verbose_name =_('Month'),help_text=_('Month'))

我正在使用 python 2.7 和 django 1.6.7。

使用calendar模块,

import calendar

values = SAPAdjustment.objects.filter(acct_per_num__range=[1, 12]
                                      ).values_list('acct_per_num', flat=True
                                                    ).distinct().order_by('acct_per_num'
                                                                          )
month_choices = [(value, calendar.month_name[value]) for value in values]

from django import forms


class SAPReconForm(forms.Form):
    month = forms.ChoiceField(choices=month_choices)

此外,使用 ChoiceField(...) 而不是 ModelChoiceField