Set Django IntegerField by choices=… name

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

    I'd probably set up the reverse-lookup dict once and for all, but if I hadn't I'd just use:

    thing.priority = next(value for value, name in Thing.PRIORITIES
                          if name=='Normal')
    

    which seems simpler than building the dict on the fly just to toss it away again;-).

提交回复
热议问题