Django如何访问抽象的Base模型局部变量 [英] Django how to access an abstract Base model local variables
问题描述
我已经定义了这个抽象的基本模型如下:
I have defined this abstract base model as below:
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
I then inherit this abstract model as below and added the new field writing
class Fluency(ActivityAbstractBaseModel):
writing = models.CharField(max_length=50, choices=STATE, default=GOOD)
现在,这个新字段 writing
正在尝试访问在抽象类中创建的变量 GOOD
和 STATE
但我有NameError
异常.有没有办法得到这些变量?
Now, this new field writing
is trying to access the variable GOOD
and STATE
that was created in the abstract class but I am having the NameError
exception. Is there a way to get these variables?
推荐答案
虽然您的类将继承这些类变量,但是您的代码不能在您定义类的地方直接引用它们(因为它们不存在于该范围内).相反,您可以在类声明中将它们称为 ActivityAbstractBaseModel.GOOD
等.
Although your class will inherit those class variables but the code you cannot directly refer them where you define your class (because they don't exist in that scope). Instead you can refer to them as ActivityAbstractBaseModel.GOOD
, etc. inside your class declaration.
class Fluency(ActivityAbstractBaseModel):
writing = models.CharField(max_length=50, choices=ActivityAbstractBaseModel.STATE, default=ActivityAbstractBaseModel.GOOD)
print(Fluency.GOOD) # This works properly
这篇关于Django如何访问抽象的Base模型局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!