python - 为什么 get_field_name_display() 不起作用?

标签 python django

我有一些使用 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`

关于python - 为什么 get_field_name_display() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25064271/

相关文章:

python - asp.net 破解 sessionId 使用 python 脚本被暴力破解的可能性

python - Django - 以geoJSON格式获取多边形的质心

Python - 在远程服务器上放置一个看起来像 json 的字符串,但引号被删除

python - 通过 'relationship' 中定义的链接对结果进行排序

django - 基于类的 View 有什么优势?

python - Stop Piston 的错误捕获

django - 删除从组继承的用户的权限 - Django

python - Django Selenium 测试,创建用户并检查登录

python - 这是httplib2的错误吗

python - 如何将 OpenCV 图像与颜色进行比较