How to properly use the “choices” field option in Django

前端 未结 7 2121
孤独总比滥情好
孤独总比滥情好 2020-12-12 23:17

I\'m reading the tutorial here: https://docs.djangoproject.com/en/1.5/ref/models/fields/#choices and i\'m trying to create a box where the user can select the month he was b

7条回答
  •  情话喂你
    2020-12-12 23:55

    I would suggest to use django-model-utils instead of Django built-in solution. The main advantage of this solution is the lack of string declaration duplication. All choice items are declared exactly once. Also this is the easiest way for declaring choices using 3 values and storing database value different than usage in source code.

    from django.utils.translation import ugettext_lazy as _
    from model_utils import Choices
    
    class MyModel(models.Model):
       MONTH = Choices(
           ('JAN', _('January')),
           ('FEB', _('February')),
           ('MAR', _('March')),
       )
       # [..]
       month = models.CharField(
           max_length=3,
           choices=MONTH,
           default=MONTH.JAN,
       )
    

    And with usage IntegerField instead:

    from django.utils.translation import ugettext_lazy as _
    from model_utils import Choices
    
    class MyModel(models.Model):
       MONTH = Choices(
           (1, 'JAN', _('January')),
           (2, 'FEB', _('February')),
           (3, 'MAR', _('March')),
       )
       # [..]
       month = models.PositiveSmallIntegerField(
           choices=MONTH,
           default=MONTH.JAN,
       )
    
    • This method has one small disadvantage: in any IDE (eg. PyCharm) there will be no code completion for available choices (it’s because those values aren’t standard members of Choices class).

提交回复
热议问题