本文介绍了设置Django IntegerField的选择= ...名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您有一个包含选项选项的模型字段时,您往往会有一些与人类可读名称相关联的魔术值。 Django有没有一个方便的方法来设置这些字段的人的可读名称而不是值?



考虑这个模型:



pre> class Thing(models.Model):
PRIORITIES =(
(0,'Low'),
(1,'Normal '),
(2,'High'),


priority = models.IntegerField(默认= 0,选择= PRIORITIES)

在某些时候,我们有一个Thing实例,我们要设置它的优先级。显然你可以做,

  thing.priority = 1 

但是这会迫使你记住优先权的Value-Name映射。这不起作用:

  thing.priority ='Normal'#在.save()上抛出ValueError 

目前我有这个愚蠢的解决方法:

 code> thing.priority = dict((key,value)for(value,key)in Thing.PRIORITIES)['Normal'] 

但这很笨重。鉴于这种情况可能是多么常见,我想知道是否有人有更好的解决方案。有没有一些字段方法用于通过选择名称设置字段,我完全忽视了

解决方案

做为。那么你可以使用一个代表正确整数的单词。



像这样:

  LOW = 0 
NORMAL = 1
HIGH = 2
STATUS_CHOICES =(
(LOW,'Low'),
(NORMAL,'Normal' ),
(HIGH,'High'),

然后他们在DB中仍然是整数。



使用将是 thing.priority = Thing.NORMAL


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?

Consider this model:

class Thing(models.Model):
  PRIORITIES = (
    (0, 'Low'),
    (1, 'Normal'),
    (2, 'High'),
  )

  priority = models.IntegerField(default=0, choices=PRIORITIES)

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 seen here. Then you can use a word that represents the proper integer.

Like so:

LOW = 0
NORMAL = 1
HIGH = 2
STATUS_CHOICES = (
    (LOW, 'Low'),
    (NORMAL, 'Normal'),
    (HIGH, 'High'),
)

Then they are still integers in the DB.

Usage would be thing.priority = Thing.NORMAL

这篇关于设置Django IntegerField的选择= ...名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 07:34