Skip to main content
 首页 » 编程设计

python之为什么 get_field_name_display() 不起作用

2025年05月04日8落叶无声

我有一些使用 get_field_name_display() 的代码.

这是发生了什么:

class Obj(models.model): 
  CHOICES = ((0, 'Foo'), 
             (1, 'Bar'), 
             (2, 'Baz')) 
  x = models.IntegerField(choices=CHOICES) 
  description = models.CharField(max_length=200) 
  ... 
 
 
obj = Obj(x=0) 
obj.description = obj.get_x_display() + ' ' + obj.id 
obj.description # Expected: 'Foo 21' 

此代码在 shell 中运行良好,但是当代码在开发服务器中运行时,生成的描述为 0 21。这是怎么回事?

请注意,在调用 get_x_display() 之前保存对象并不能解决这个问题。从数据库中获取对象的新副本可以,但这太可怕了,我宁愿不这样做。

请您参考如下方法:

尝试使用

class Obj(models.model): 
    CHOICES = ((0, 'Foo'), 
         (1, 'Bar'), 
         (2, 'Baz')) 
    x = models.IntegerField(choices=CHOICES) 
    description = models.CharField(max_length=200) 
 
 
 
   @property 
   def nu(self): 
       return self.get_x_display() 

并在 :obj.description = obj.nu + ' ' + obj.id`