【问题标题】:Show month name instead of month number (fetched from db) in django model choice field在 django 模型选择字段中显示月份名称而不是月份编号(从 db 获取)
【发布时间】:2020-08-06 09:25:17
【问题描述】:
SAPAdjustment 中的

acct_per_num 包含月份编号。以下代码提供了一个下拉列表,其中包含唯一月份编号 (1,2,3),列中存在于表 SAPAdjustment 的列 acct_per_num 但我想要月份名称(一月、二月、三月)而不是月份数字 (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。

【问题讨论】:

    标签: django django-models django-forms django-orm


    【解决方案1】:

    使用 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 2023-03-27
      • 2022-01-25
      • 2017-12-17
      • 2014-02-24
      相关资源
      最近更新 更多