Set Django IntegerField by choices=… name

后端 未结 10 857
南笙
南笙 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:04

    As of Django 3.0, you can use:

    class ThingPriority(models.IntegerChoices):
        LOW = 0, 'Low'
        NORMAL = 1, 'Normal'
        HIGH = 2, 'High'
    
    
    class Thing(models.Model):
        priority = models.IntegerField(default=ThingPriority.LOW, choices=ThingPriority.choices)
    
    # then in your code
    thing = get_my_thing()
    thing.priority = ThingPriority.HIGH
    

提交回复
热议问题