Django 如何访问一个抽象的 Base 模型局部变量
Django how to access an abstract Base model local variables
我定义了这个抽象基础模型如下:
class ActivityAbstractBaseModel(models.Model):
POOR = 'PR'
FAIR = 'FA'
MEDIOCRE = 'ME'
GOOD_ENOUGH = 'GE'
GOOD = 'GO'
VERY_GOOD = 'VG'
EXCELLENT = 'EX'
STATE = [
(POOR, 'Poor'),
(FAIR, 'Fair'),
(MEDIOCRE,'Mediocre' ),
(GOOD_ENOUGH, 'Good Enough' ),
(GOOD, 'Good'),
(VERY_GOOD, 'Very Good'),
(EXCELLENT, 'Excellent'),
]
speaking = models.CharField(max_length=50, choices=STATE, default=GOOD)
然后我如下继承这个抽象模型并添加新字段writing
class Fluency(ActivityAbstractBaseModel):
writing = models.CharField(max_length=50, choices=STATE, default=GOOD)
现在,这个新字段 writing
正在尝试访问在摘要 class 中创建的变量 GOOD
和 STATE
但我有 NameError
异常。有没有办法获取这些变量?
虽然您的 class 将继承那些 class 变量,但是您不能在定义 class 的地方直接引用它们的代码(因为它们不存在于该范围内)。相反,您可以在 class 声明中将它们称为 ActivityAbstractBaseModel.GOOD
等。
class Fluency(ActivityAbstractBaseModel):
writing = models.CharField(max_length=50, choices=ActivityAbstractBaseModel.STATE, default=ActivityAbstractBaseModel.GOOD)
print(Fluency.GOOD) # This works properly
我定义了这个抽象基础模型如下:
class ActivityAbstractBaseModel(models.Model):
POOR = 'PR'
FAIR = 'FA'
MEDIOCRE = 'ME'
GOOD_ENOUGH = 'GE'
GOOD = 'GO'
VERY_GOOD = 'VG'
EXCELLENT = 'EX'
STATE = [
(POOR, 'Poor'),
(FAIR, 'Fair'),
(MEDIOCRE,'Mediocre' ),
(GOOD_ENOUGH, 'Good Enough' ),
(GOOD, 'Good'),
(VERY_GOOD, 'Very Good'),
(EXCELLENT, 'Excellent'),
]
speaking = models.CharField(max_length=50, choices=STATE, default=GOOD)
然后我如下继承这个抽象模型并添加新字段writing
class Fluency(ActivityAbstractBaseModel):
writing = models.CharField(max_length=50, choices=STATE, default=GOOD)
现在,这个新字段 writing
正在尝试访问在摘要 class 中创建的变量 GOOD
和 STATE
但我有 NameError
异常。有没有办法获取这些变量?
虽然您的 class 将继承那些 class 变量,但是您不能在定义 class 的地方直接引用它们的代码(因为它们不存在于该范围内)。相反,您可以在 class 声明中将它们称为 ActivityAbstractBaseModel.GOOD
等。
class Fluency(ActivityAbstractBaseModel):
writing = models.CharField(max_length=50, choices=ActivityAbstractBaseModel.STATE, default=ActivityAbstractBaseModel.GOOD)
print(Fluency.GOOD) # This works properly