Set Django IntegerField by choices=… name

后端 未结 10 868
南笙
南笙 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

    class Sequence(object):
        def __init__(self, func, *opts):
            keys = func(len(opts))
            self.attrs = dict(zip([t[0] for t in opts], keys))
            self.choices = zip(keys, [t[1] for t in opts])
            self.labels = dict(self.choices)
        def __getattr__(self, a):
            return self.attrs[a]
        def __getitem__(self, k):
            return self.labels[k]
        def __len__(self):
            return len(self.choices)
        def __iter__(self):
            return iter(self.choices)
        def __deepcopy__(self, memo):
            return self
    
    class Enum(Sequence):
        def __init__(self, *opts):
            return super(Enum, self).__init__(range, *opts)
    
    class Flags(Sequence):
        def __init__(self, *opts):
            return super(Flags, self).__init__(lambda l: [1<

    Use it like this:

    Priorities = Enum(
        ('LOW', 'Low'),
        ('NORMAL', 'Normal'),
        ('HIGH', 'High')
    )
    
    priority = models.IntegerField(default=Priorities.LOW, choices=Priorities)
    

提交回复
热议问题