Set Django IntegerField by choices=… name

后端 未结 10 878
南笙
南笙 2020-12-07 09:40

When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these f

10条回答
  •  半阙折子戏
    2020-12-07 10:14

    Here's a field type I wrote a few minutes ago that I think does what you want. Its constructor requires an argument 'choices', which may be either a tuple of 2-tuples in the same format as the choices option to IntegerField, or instead a simple list of names (ie ChoiceField(('Low', 'Normal', 'High'), default='Low') ). The class takes care of the mapping from string to int for you, you never see the int.

      class ChoiceField(models.IntegerField):
        def __init__(self, choices, **kwargs):
            if not hasattr(choices[0],'__iter__'):
                choices = zip(range(len(choices)), choices)
    
            self.val2choice = dict(choices)
            self.choice2val = dict((v,k) for k,v in choices)
    
            kwargs['choices'] = choices
            super(models.IntegerField, self).__init__(**kwargs)
    
        def to_python(self, value):
            return self.val2choice[value]
    
        def get_db_prep_value(self, choice):
            return self.choice2val[choice]
    

提交回复
热议问题