如果您有一个带有选项选项的模型字段,您往往会有一些与人类可读名称相关联的魔术值。在Django中是否可以通过人类可读的名称而不是值来设置这些字段?
考虑这个模型:
class Thing(models.Model):
PRIORITIES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),
)
priority = models.IntegerField(default=0, choices=PRIORITIES)
在某些时候,我们有一个Thing实例,我们想要设置它的优先级。显然你可以做到,
thing.priority = 1
但是这会迫使你记住PRIORITIES的Value-Name映射。这不起作用:
thing.priority = 'Normal' # Throws ValueError on .save()
目前我有这个愚蠢的解决方法:
thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal']
但那很笨重。考虑到这种情况有多常见,我想知道是否有人有更好的解决方案。是否有一些字段方法可以通过选择名称设置字段,我完全忽略了它?
答案 0 :(得分:149)
执行seen here。然后你可以使用一个代表正确整数的单词。
像这样:
LOW = 0
NORMAL = 1
HIGH = 2
STATUS_CHOICES = (
(LOW, 'Low'),
(NORMAL, 'Normal'),
(HIGH, 'High'),
)
然后它们仍然是数据库中的整数。
用法为thing.priority = Thing.NORMAL
答案 1 :(得分:9)
从Django 3.0开始,您可以使用:
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
答案 2 :(得分:7)
我可能会一劳永逸地设置反向查找词典,但如果我没有,我只会使用:
thing.priority = next(value for value, name in Thing.PRIORITIES
if name=='Normal')
这似乎比在飞行中制作dict更简单,只是为了把它扔掉; - )。
答案 3 :(得分:5)
这是我几分钟前写的一个字段类型,我觉得你做的就是你想要的。它的构造函数需要一个参数'choices',它可以是与IntegerField的choices选项格式相同的2元组元组,或者是一个简单的名字列表(即ChoiceField(('Low','Normal', '高'),默认='低'))。该类负责处理从string到int的映射,你永远不会看到int。
class ChoiceField(models.IntegerField):
def __init__(self, choices, **kwargs):
if not hasattr(choices[0],'__iter__'):
choices = zip(range(len(choices)), choices)
self.val2choice = dict(choices)
self.choice2val = dict((v,k) for k,v in choices)
kwargs['choices'] = choices
super(models.IntegerField, self).__init__(**kwargs)
def to_python(self, value):
return self.val2choice[value]
def get_db_prep_value(self, choice):
return self.choice2val[choice]
答案 4 :(得分:3)
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<<i for i in xrange(l)], *opts)
像这样使用:
Priorities = Enum(
('LOW', 'Low'),
('NORMAL', 'Normal'),
('HIGH', 'High')
)
priority = models.IntegerField(default=Priorities.LOW, choices=Priorities)
答案 5 :(得分:2)
我很欣赏不断定义的方式,但我相信Enum类型对于这项任务来说是最好的。它们可以同时表示项目的整数和字符串,同时保持代码更具可读性。
在3.4版本中将枚举引入Python。如果您使用任何较低版本(例如v2.x),您仍可以通过安装backported package:pip install enum34
来获取它。
# myapp/fields.py
from enum import Enum
class ChoiceEnum(Enum):
@classmethod
def choices(cls):
choices = list()
# Loop thru defined enums
for item in cls:
choices.append((item.value, item.name))
# return as tuple
return tuple(choices)
def __str__(self):
return self.name
def __int__(self):
return self.value
class Language(ChoiceEnum):
Python = 1
Ruby = 2
Java = 3
PHP = 4
Cpp = 5
# Uh oh
Language.Cpp._name_ = 'C++'
这几乎就是全部。您可以继承ChoiceEnum
来创建自己的定义,并在模型定义中使用它们,如:
from django.db import models
from myapp.fields import Language
class MyModel(models.Model):
language = models.IntegerField(choices=Language.choices(), default=int(Language.Python))
# ...
你可能会猜到,查询是锦上添花:
MyModel.objects.filter(language=int(Language.Ruby))
# or if you don't prefer `__int__` method..
MyModel.objects.filter(language=Language.Ruby.value)
将它们表示在字符串中也很简单:
# Get the enum item
lang = Language(some_instance.language)
print(str(lang))
# or if you don't prefer `__str__` method..
print(lang.name)
# Same as get_FOO_display
lang.name == some_instance.get_language_display()
答案 6 :(得分:1)
只需用您想要的人类可读值替换您的数字。就这样:
PRIORITIES = (
('LOW', 'Low'),
('NORMAL', 'Normal'),
('HIGH', 'High'),
)
这使得它具有人类可读性,但是,您必须定义自己的顺序。
答案 7 :(得分:1)
我的答案很晚,现在看起来很明显 - Django专家,但对于任何人来到这里,我最近发现了django-model-utils带来的一个非常优雅的解决方案:https://django-model-utils.readthedocs.io/en/latest/utilities.html#choices
此软件包允许您定义具有三元组的选项,其中:
所以,你可以做什么:
from model_utils import Choices
class Thing(models.Model):
PRIORITIES = Choices(
(0, 'low', 'Low'),
(1, 'normal', 'Normal'),
(2, 'high', 'High'),
)
priority = models.IntegerField(default=PRIORITIES.normal, choices=PRIORITIES)
thing.priority = getattr(Thing.PRIORITIES.Normal)
这样:
享受:)
答案 8 :(得分:1)
模型的choices选项接受一个序列,该序列本身由正好由两项组成的可迭代项组成(例如[(A,B),(A,B)...]),用作该字段的选择。
此外,Django提供了enumeration types,您可以将其子类化以简洁的方式定义选择:
class ThingPriority(models.IntegerChoices):
LOW = 0, _('Low')
NORMAL = 1, _('Normal')
HIGH = 2, _('High')
class Thing(models.Model):
priority = models.IntegerField(default=ThingPriority.NORMAL, choices=ThingPriority.choices)
Django支持在该元组的末尾添加一个额外的字符串值,以用作人类可读的名称或标签。标签可以是懒惰的可翻译字符串。
# in your code
thing = get_thing() # instance of Thing
thing.priority = ThingPriority.LOW
注意:您可以使用ThingPriority.HIGH
,ThingPriority.['HIGH']
或ThingPriority(0)
来访问或查找枚举成员。
答案 9 :(得分:0)
最初,我使用@Allan答案的修改版本:
from enum import IntEnum, EnumMeta
class IntegerChoiceField(models.IntegerField):
def __init__(self, choices, **kwargs):
if hasattr(choices, '__iter__') and isinstance(choices, EnumMeta):
choices = list(zip(range(1, len(choices) + 1), [member.name for member in list(choices)]))
kwargs['choices'] = choices
super(models.IntegerField, self).__init__(**kwargs)
def to_python(self, value):
return self.choices(value)
def get_db_prep_value(self, choice):
return self.choices[choice]
models.IntegerChoiceField = IntegerChoiceField
GEAR = IntEnum('GEAR', 'HEAD BODY FEET HANDS SHIELD NECK UNKNOWN')
class Gear(Item, models.Model):
# Safe to assume last element is largest value member of an enum?
#type = models.IntegerChoiceField(GEAR, default=list(GEAR)[-1].name)
largest_member = GEAR(max([member.value for member in list(GEAR)]))
type = models.IntegerChoiceField(GEAR, default=largest_member)
def __init__(self, *args, **kwargs):
super(Gear, self).__init__(*args, **kwargs)
for member in GEAR:
setattr(self, member.name, member.value)
print(Gear().HEAD, (Gear().HEAD == GEAR.HEAD.value))
我现在使用的django-enumfields
软件包简化了:
from enumfields import EnumIntegerField, IntEnum
GEAR = IntEnum('GEAR', 'HEAD BODY FEET HANDS SHIELD NECK UNKNOWN')
class Gear(Item, models.Model):
# Safe to assume last element is largest value member of an enum?
type = EnumIntegerField(GEAR, default=list(GEAR)[-1])
#largest_member = GEAR(max([member.value for member in list(GEAR)]))
#type = EnumIntegerField(GEAR, default=largest_member)
def __init__(self, *args, **kwargs):
super(Gear, self).__init__(*args, **kwargs)
for member in GEAR:
setattr(self, member.name, member.value)