通过 selection=... name 设置 Django IntegerField [英] Set Django IntegerField by choices=... name
问题描述
当您有一个带有选择选项的模型字段时,您往往会有一些与人类可读名称相关联的魔法值.Django 中是否有一种方便的方法可以通过人类可读的名称而不是值来设置这些字段?
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 fields by the human readable name instead of the value?
考虑这个模型:
class Thing(models.Model):
PRIORITIES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),
)
priority = models.IntegerField(default=0, choices=PRIORITIES)
在某些时候,我们有一个 Thing 实例,我们想设置它的优先级.显然你可以做到,
At some point we have a Thing instance and we want to set its priority. Obviously you could do,
thing.priority = 1
但这迫使您记住优先级的值-名称映射.这不起作用:
But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work:
thing.priority = 'Normal' # Throws ValueError on .save()
目前我有这个愚蠢的解决方法:
Currently I have this silly workaround:
thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal']
但这很笨拙.鉴于这种情况有多常见,我想知道是否有人有更好的解决方案.是否有一些字段方法可以通过我完全忽略的选择名称设置字段?
but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?
推荐答案
Do as 见这里.然后你可以使用一个代表正确整数的词.
Do as seen here. Then you can use a word that represents the proper integer.
像这样:
LOW = 0
NORMAL = 1
HIGH = 2
STATUS_CHOICES = (
(LOW, 'Low'),
(NORMAL, 'Normal'),
(HIGH, 'High'),
)
那么它们在数据库中仍然是整数.
Then they are still integers in the DB.
用法为 thing.priority = Thing.NORMAL
这篇关于通过 selection=... name 设置 Django IntegerField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!