【问题标题】:Get the name or labe from django IntegerChoices providing a valid value从 django IntegerChoices 获取名称或标签,提供有效值
【发布时间】:2021-12-16 15:26:36
【问题描述】:

我有 django 3.2 和一个 IntegerChoices 类

 class Type(models.IntegerChoices):
        GENERAL = 2, _("general address")
        DELIVERY = 4, _("delivery address")
        BILLING = 6, _("billing address")

我可以通过执行 Type.GENERAL 、 Type.GENERAL.name 和 Type.GENERAL.label 轻松获取值名称和标签。

但是如果我只有值,我怎么能得到这些值,例如我想从值 4 中获取名称 DELIVERY。

Type[4].name 不起作用,因为列表值与枚举的 int 值不对应。

谢谢 马特

【问题讨论】:

    标签: python python-3.x django


    【解决方案1】:

    IntegerChoices.choices 返回一个包含所有内容的元组列表。在你的情况下,你会有类似的东西:

    [(2, 'general address'), (4, 'delivery address'), (6, 'billing address')]
    

    因此可以这样做:

    class Type(models.IntegerChoices):
        GENERAL = 2, _("general address")
        DELIVERY = 4, _("delivery address")
        BILLING = 6, _("billing address")
    
    def label_by_type_value(value):
        choices = [c[1] for c in Type.choices if c[0] == value]
        return choices[0] if len(choices) else None
    

    【讨论】:

    • 是的,我已经看到了,我认为有一种内置方法可以做到这一点。也许这个用例太少见了。
    【解决方案2】:

    如果你能确定它是一个有效值,你也可以这样做:

    print(Type(2).name)    
    print(Type(2).label)
    

    【讨论】:

      猜你喜欢
      • 2020-07-15
      • 1970-01-01
      • 2015-08-24
      • 1970-01-01
      • 2015-10-27
      • 1970-01-01
      • 2015-05-14
      • 2020-12-21
      • 2021-07-10
      相关资源
      最近更新 更多