【问题标题】:Accessing django model attribute passed as a parameter访问作为参数传递的 django 模型属性
【发布时间】:2020-11-09 11:11:13
【问题描述】:

我将 django 与旧数据库一起使用,在该数据库中我无法更改原始表列。我有类似的模型,它们的字段名称略有不同。下面的模型就是一个例子。

class EURegister(models.Model):
    record_id = models.AutoField(primary_key=True)
    reg_no = models.CharField(max_length=45, blank=True, null=True)
    company_name = models.CharField(max_length=300, blank=True, null=True)

在某些型号中,reg_no 是不同的名称,例如 registration_id。因此,我必须访问作为参数传递的模型属性。但我不能使用它,因为模型不允许使用属性,因为它们是dict 键。它给出了以下错误。

TypeError: 'EURegister' object is not subscriptable

【问题讨论】:

    标签: django


    【解决方案1】:

    您可以使用getattr(…) [python-doc]:

    <b>getattr(</b><i>myeuregister</i>, 'reg_no'<b>)</b>

    所以getattr(x, 'y') 等价于x.y。

    话虽如此,如果不同的模型(非常)相似,那么将这些模型“合并”到一个模型中可能更有意义。对相同类型的对象使用不同的表通常不是很好的设计。

    【讨论】:

      猜你喜欢
      • 2011-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 2015-04-19
      • 2011-08-15
      • 2016-06-21
      • 2019-05-18
      相关资源
      最近更新 更多